[英]Call method of included module from class
I have a use case where I have class A
which includes module B
. 我有一个用例,其中有包含module B
class A
class A
include B
def do_one_thing
# override module's method. do something different instead
end
def do_another_thing
# Call `do_one_thing` from here,
# but call the module's method, not the one I overrode above.
end
end
module B
included do
def do_one_thing
# ...
end
end
# some other methods
end
As shown above, I'm calling do_one_thing
from do_another_thing
. 如上图所示,我打电话do_one_thing
从do_another_thing
。 My problem is that I need to call the module's method (ie the super
method). 我的问题是我需要调用模块的方法(即super
方法)。 Is this possible in Rails? 在Rails中可能吗?
To property use the included
method, you'll need your B
module to extend ActiveSupport::Concern
but that won't give you the behaviour you want. 要使用所included
方法进行属性设置,您将需要B
模块extend ActiveSupport::Concern
但这不会为您提供所需的行为。
If I were you I'd abandon that pattern and use simple native Ruby module patterns: 如果您是我,我将放弃该模式,而使用简单的本机Ruby模块模式:
module B
def do_one_thing
puts 'in module'
# ...
end
# some other methods
end
class A
include B
def do_one_thing
super
puts 'in class'
# override module's method. do something different instead
end
def do_another_thing
do_one_thing
# Call `do_one_thing` from here,
# but call the module's method, not the one I overrode above.
end
end
A.new.do_one_thing
The above code will correctly use the module inheritance you are looking for. 上面的代码将正确使用您要查找的模块继承。
Read more about Ruby module inheritance here 在此处阅读有关Ruby模块继承的更多信息
You can 'save' included method before override 您可以在覆盖之前“保存”包含的方法
module B
extend ActiveSupport::Concern
included do
def do_one_thing
puts 'do_one_thing'
end
end
end
class A
include B
alias_method :old_do_one_thing, :do_one_thing
def do_one_thing
puts "I'd rather do this"
end
def do_another_thing
old_do_one_thing
end
end
a= A.new
a.do_one_thing
a.do_another_thing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.