好的,我有点新手。我知道这个错误正在发生,因为我没有正确理解如何调用方法。所以你能帮我理解这里出了什么问题吗?
ThingController #index中的NoMethodError 未定义的方法`已初始化?' for Thing :: Backend:Class
来自ThingController.rb的错误部分:
class ThingController
def init_things
Backend.init_things unless Backend.initialized?
end
t = ThingController.new
t.init_things
end
在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
我没有正确地调用该方法,我在互联网上找不到任何关于此错误的明确解释。请帮忙。
由于
答案 0 :(得分:5)
看来问题是你在Backend
中声明的初始化方法是一个实例方法。当您调用Backend.initialized?
时,您正在调用initialized?
类的类方法Backend
。此方法未定义,因此它会引发NoMethodError
。您可以通过使用def self.initialized?
声明方法来解决此问题。如果您真的希望这是一个类方法,您可能需要考虑如何组织其余代码。
您可以在http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/
找到有关课程与实例方法的更多信息答案 1 :(得分:2)
您已将initialized?
声明为实例方法,但它正在调用它,就像它是一个类方法一样。 Here's an explanation of the difference between instance methods and class methods.