在class_eval中使用super [英] Using super with class_eval
问题描述
我有一个应用程序,该模块在核心类中包含用于添加客户端自定义项的模块.
I have an app that includes modules into core Classes for adding client customizations.
我发现class_eval是重写核心Class中的方法的好方法,但是有时候我想避免重写整个方法,而只是遵循原始方法.
I'm finding that class_eval is a good way to override methods in the core Class, but sometimes I would like to avoid re-writing the entire method, and just defer to the original method.
例如,如果我有一个名为account_balance
的方法,那么最好在我的模块(即包含在Class中的模块)中做类似的事情:
For example, if I have a method called account_balance
, it would be nice to do something like this in my module (i.e. the module that gets included into the Class):
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
方法脱离查找路径.
But using class_eval seems to take the super
method out of the lookup path.
有人知道如何解决此问题吗?
Does anyone know how to work around this?
谢谢!
推荐答案
我认为有几种方法可以完成您想做的事情.一种是打开类并为旧的实现加上别名:
I think there are several ways to do what you're wanting to do. One is to open the class and alias the old implementation:
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
这是猴子补丁的一种形式,因此最好在适度.另外,有时需要的是一个单独的辅助方法,该方法具有通用功能.
This is a form of monkey patching, so probably best to make use of the idiom in moderation. Also, sometimes what is wanted is a separate helper method that holds the common functionality.
编辑:有关更全面的选项,请参见JörgW Mittag的答案.
EDIT: See Jörg W Mittag's answer for a more comprehensive set of options.
这篇关于在class_eval中使用super的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!