我需要在父类的每个子类中注入回调函数。因此,带有回调函数的方法必须首先被调用,然后再调用所有后续链:
但是通过继承实现这一点是否可能?例如在ChildMod1或ChildMod2中。我希望能在一个模块空间内执行代码,以获得继承的所有优势。
假设我有一个类方法"field",它会向Datastream添加一些实例方法(例如添加setter和getter方法),我想重新定义其中的一个方法,就像这样:
可以通过alias_method(或alias_method_chain)实现:
module ChildMod1
def save
puts "save ChildMod1"
super
end
end
module ChildMod2
def save
puts "save ChildMod2"
super
end
end
class Parent
def save
puts "save Parent"
end
end
class Child < Parent
include ChildMod1
include ChildMod2
def save
puts "save Child"
super
end
alias_method :old_save, :save
module_eval <<-R
def save
puts "save Callback"
old_save
end
R
end
c = Child.new
c.save
输出
save Callback
save Child
save ChildMod2
save ChildMod1
save Parent
但是通过继承实现这一点是否可能?例如在ChildMod1或ChildMod2中。我希望能在一个模块空间内执行代码,以获得继承的所有优势。
module ChildMod1
def save
puts "save ChildMod1"
super
end
end
module ChildMod2
def save
puts "save ChildMod2"
super
end
end
class Parent
def save
puts "save Parent"
end
end
class Child < Parent
include ChildMod1
include ChildMod2
def save
puts "save Child"
super
end
module_eval <<-R
def save
puts "save Callback"
super
end
R
end
c = Child.new
c.save
输出
save Callback
save ChildMod2
save ChildMod1
save Parent
正如您所看到的,它只覆盖了Child。
更新 wdebeaum的解决方案很好,但是如果我需要通过module_eval或类似方法动态地创建许多方法,并在类内部重新定义它们呢?我不能为它们创建单独的模块。
class TestEval
def redefine_me
puts "Test method"
super # I expect that it will call Eval method, but module_eval just overwrite it
end
module_eval <<-R
def redefine_me
puts "Eval method"
end
R
end
更新2:使用单例模式,我得到了错误的链式评估顺序Eval => Test,而不是正确的Test => Eval。
class TestEval
def initialize
class << self
def redefine_me
puts "Eval method"
super
end
end
end
def redefine_me
puts "Test method"
end
end
TestEval.new.redefine_me
假设我有一个类方法"field",它会向Datastream添加一些实例方法(例如添加setter和getter方法),我想重新定义其中的一个方法,就像这样:
class Datastream
field :name
def name=(value)
puts "redefined!"
super
end
end