Ruby / RoR:通过super()调用原始方法?
在RoR应用程序中,我想在我的一个模型中专门化ActiveRecord的update_attributes()方法,提取一些特殊处理的属性,并将其余的属性传递给原始的update_attributes()方法。 细节:
class Premise < ActiveRecord::Base ... def update_attributes(attrs) attrs.each_pair do |key, val| unless has_attribute?(key) do_special_processing(key, val) attrs.delete(key) end end # use original update_attributes() to process non-special pairs super.update_attributes(attrs) end ... end
对super.update_attributes(attr)的调用引发了一个错误:
undefined method `update_attributes' for true:TrueClass
…这让我怀疑我真的不理解Ruby中的super关键字。 我错过了什么? 具体来说,我如何调用原始的update_attributes()方法?
你要:
super(attrs)
这将调用原始方法,将attrs作为参数传递给它。
就像现在一样,您正在尝试在原始update_attributes返回的“true”值上调用update_attributes。
在Ruby中,super是一个特殊情况,其中括号确实很重要……
在子类的方法中调用super
而不使用参数(也不是括号)会在super
类中调用相同的方法(如果超类没有定义它,则调用其祖先),并将所有参数传递给子类方法。 所以,在这里,你可以写简单超级。
调用super()
调用不带任何参数的超类(或祖先)方法(假设此方法不接受任何参数……)
使用任何参数组合调用super(...)
调用超类方法,并将其传递给参数
这看起来更适合alias_method_chain:
def update_attributes_with_special(attrs) attrs.each_pair do |key, val| unless has_attribute?(key) do_special_processing(key, val) attrs.delete(key) end end update_attributes_without_special(attrs) end alias_method_chain :update_attributes, :special