![](/img/trans.png)
[英]Is it okay to call a private method of a parent class's subclass from a module which is included in the parent class in rails?
[英]Call method of included module from class
我有一個用例,其中有包含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
如上圖所示,我打電話do_one_thing
從do_another_thing
。 我的問題是我需要調用模塊的方法(即super
方法)。 在Rails中可能嗎?
要使用所included
方法進行屬性設置,您將需要B
模塊extend ActiveSupport::Concern
但這不會為您提供所需的行為。
如果您是我,我將放棄該模式,而使用簡單的本機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
上面的代碼將正確使用您要查找的模塊繼承。
您可以在覆蓋之前“保存”包含的方法
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.