我有一个应用程序,其中包括模块到核心类,以添加客户端自定义。
我发现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方法从查找路径中移除。
有人知道如何解决这个问题吗?
谢谢!
发布于 2012-12-11 03:30:41
我发现instance_eval是覆盖核心类中方法的好方法,
您不是在重写。您正在覆盖aka monkeypatching。
,但有时我想避免重写整个方法,而只遵循原始方法。
你不能遵从原来的方法。没有原创的方法。你把它改写了。
,但使用instance_eval似乎会将
super方法从查找路径中删除。
在您的示例中没有继承。super甚至都不起作用。
有关可能的解决方案和替代方案,请参阅此答案:When monkey patching a method, can you call the overridden method from the new implementation?
https://stackoverflow.com/questions/13806630
复制相似问题