开发者

Ruby NoMethodError

Ok, I'm a bit of a newb. I know this error is occuring because I don't properly understand something about how methods are called. So can you help me understand what is going wrong here?

NoMethodError in ThingController#index undefined method `initialized?' for Thing::Backend:Class

From the erroring section of ThingController.rb:

class ThingController
  def init_things
   Backend.init_things unless Backend.initialized?    
  end

  t = Th开发者_如何学运维ingController.new 
  t.init_things
end

inside Backend.rb

class Backend
  # checks if the things hash is initialized
  def initialized?
    @initialized ||= false
  end

  # loads things
  def init_things
    puts "I've loaded a bunch of files into a hash"
    @initialized = true
  end
end

I'm not calling the method correctly and I cannot find any clear explanations for this error on the internet. Please help.

Thanks


It appears that the issue is that the initialized method that you have declared in Backend is an instance method. When you then call Backend.initialized? you are calling calling the class method initialized? for the Backend class. This method is not defined, and so it raises the NoMethodError. You can solve this by declaring the method using def self.initialized?. If you really want this to be a class method, you may need to consider how the rest of your code is organized.

You can find more information on class vs. instance methods at http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/


You've declared initialized? as an instance method but are calling it as if it were a class method. Here's an explanation of the difference between instance methods and class methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜