如何从 rake 中调用 class 包含的模块函数?
How to call an class's included module function from a rake?
我正在执行 rake 文件中的任务。
# gottaRunThis.rake
task [:var] => :environment do |t, args|
Foo::Bar::Bell::this_function(args.var)
#runs Bell::this_function(var) but fails to complete.
# errors out with the words:
# NoMethodError: undefined method `put' for nil:NilClass
# Because Bell needs a @connection variable that doesn't exist in
# it's context when called directly.
end
问题是,目标模块和 def 应该包含在另一个 class。
# mainclass.rb
module Foo
module Bar
class TheMainClass
include Foo::Bar::Bell
def initialize
@site = A_STATIC_SITE_VARIABLE
@connection = self.connection
end
def connection
# Connection info here, too verbose to type up
end
end
end
end
和Bell
长得像。
# bell.rb
module Foo
module Bar
module Bell
def do_the_thing(var)
#things happen here
#var converted to something here
response = @connection.put "/some/restful/interface, var_converted
end
end
end
我是否应该修改 Bell
以使其以某种方式包含 TheMainClass
? (如果是这样,我不知道怎么做?)或者我应该在我的 rake 文件中使用一些语法,比如
Foo::Bar::TheMainClass::Bell::do_the_thing(args.var)
#I don't think this works... should it? What would the equivilent but working version look like?
包含的方法可作为实例方法使用,因此您可以这样调用 do_the_thing
:
main_class = Foo::Bar::TheMainClass.new
main_class.do_the_thing(args.var)
我正在执行 rake 文件中的任务。
# gottaRunThis.rake
task [:var] => :environment do |t, args|
Foo::Bar::Bell::this_function(args.var)
#runs Bell::this_function(var) but fails to complete.
# errors out with the words:
# NoMethodError: undefined method `put' for nil:NilClass
# Because Bell needs a @connection variable that doesn't exist in
# it's context when called directly.
end
问题是,目标模块和 def 应该包含在另一个 class。
# mainclass.rb
module Foo
module Bar
class TheMainClass
include Foo::Bar::Bell
def initialize
@site = A_STATIC_SITE_VARIABLE
@connection = self.connection
end
def connection
# Connection info here, too verbose to type up
end
end
end
end
和Bell
长得像。
# bell.rb
module Foo
module Bar
module Bell
def do_the_thing(var)
#things happen here
#var converted to something here
response = @connection.put "/some/restful/interface, var_converted
end
end
end
我是否应该修改 Bell
以使其以某种方式包含 TheMainClass
? (如果是这样,我不知道怎么做?)或者我应该在我的 rake 文件中使用一些语法,比如
Foo::Bar::TheMainClass::Bell::do_the_thing(args.var)
#I don't think this works... should it? What would the equivilent but working version look like?
包含的方法可作为实例方法使用,因此您可以这样调用 do_the_thing
:
main_class = Foo::Bar::TheMainClass.new
main_class.do_the_thing(args.var)