我有一个应用程序,其中包含用于添加客户端自定义的核心类模块。
我发现 class_eval 是重写核心类中方法的好方法,但有时我想避免重写整个方法,而只是遵循原始方法。
例如,如果我有一个名为account_balance
,最好在我的模块(即包含在类中的模块)中执行类似的操作:
module CustomClient
def self.included base
base.class_eval do
def account_balance
send_alert_email if balance < min
super # Then this would just defer the rest of the logic defined in the original class
end
end
end
end
但使用 class_eval 似乎需要super
方法脱离查找路径。
有谁知道如何解决这个问题?
Thanks!
我认为有几种方法可以做你想做的事。一种是打开类并为旧实现指定别名:
class MyClass
def method1
1
end
end
class MyClass
alias_method :old_method1, :method1
def method1
old_method1 + 1
end
end
MyClass.new.method1
=> 2
这是一种形式猴子修补 http://en.wikipedia.org/wiki/Monkey_patch,所以最好适度使用这个习语。此外,有时需要一个单独的辅助方法来保存通用功能。
EDIT:有关更全面的选项,请参阅 Jörg W Mittag 的答案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)