【问题标题】:Why do I get the error uninitialized constant Stuff::HTTParty?为什么我会收到错误未初始化常量 Stuff::HTTParty?
【发布时间】:2014-08-15 23:21:47
【问题描述】:

我的系统上有 HTTParty gem,我可以在 rails 中使用它。

现在我想单独使用它。

我正在尝试:

class Stuff
  include HTTParty
  def self.y
    HTTParty.get('http://www.google.com')
  end 
end
Stuff.y

但我明白了

$ ruby test_httparty.rb 
test_httparty.rb:2:in `<class:Stuff>': uninitialized constant Stuff::HTTParty (NameError)
        from test_httparty.rb:1:in `<main>'
07:46:52 durrantm Castle2012 /home/durrantm/Dropnot/_/rails_apps/linker 73845718_get_method
$ 

【问题讨论】:

    标签: ruby class methods gem httparty


    【解决方案1】:

    你必须require 'httparty':

    require 'httparty'
    
    class Stuff
      include HTTParty
      # ...
    end
    

    【讨论】:

      【解决方案2】:

      这都是因为类中存在的包含

      如果你在一个模块中包含一个类,这意味着你正在“引入”模块的方法作为实例方法。

      如果您需要更清楚地了解包含和要求

      请大家参考这篇精彩的 SO Posting

      What is the difference between include and require in Ruby?

      这是我从同一篇文章中摘录的一个例子

       module A
         def say
           puts "this is module A"
         end
       end
      
       class B
         include A
       end
      
       class C
         extend A
       end
      B.say => undefined method 'say' for B:Class
      
      B.new.say => this is module A
      
      C.say => this is module A
      
      C.new.say => undefined method 'say' for C:Class
      

      【讨论】:

      • @JörgWMittag 很抱歉,如果它不符合要求,我发布了它,因为发布问题的人如果知道这个问题就不会问这个问题。
      猜你喜欢
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      相关资源
      最近更新 更多