【发布时间】:2020-05-13 20:59:33
【问题描述】:
我想在我的模块加载时定义变量@@importers。
module Importers
@@importers_dir = File.dirname(__FILE__) + '/services/'
@@importers = self.load_and_instantiate()
def self.load_and_instantiate()
#mycode here
end
end
但它不起作用:
进口商的未定义方法'load_and_instantiate':模块 (NoMethodError)
我应该如何处理?
谢谢!
【问题讨论】:
-
我没有看到在模块中定义的类变量(并且很少看到在任何地方定义的类变量,这是有充分理由的)。我假设您意识到如果
Importers包含在一个类中,该类将获取那些具有计算值的类变量(例如,module M; @@v = 1; end; class C; include M; end; C.class_variable_get(:@@v) #=> 1)。如果创建Importers::load_and_instantiate只是为了给@@importers赋值,那么只需写@@importers = #mycode here。最后,不带参数调用方法时,通常不会显示空括号。