Ruby/RoR: calling original method via super()?

后端 未结 3 1267

In a RoR app, I want to specialize ActiveRecord\'s update_attributes() method in one of my models, extracting some of the attributes for special handling and passing the res

相关标签:
3条回答
  • 2020-12-30 05:45

    You want:

    super(attrs)
    

    That will call the original method, passing attrs as an argument to it.

    As it is now, you're trying to call update_attributes on the "true" value returned by the original update_attributes.

    0 讨论(0)
  • 2020-12-30 06:00

    In Ruby super is a special case where parenthesis do matter...

    Calling super without parameter (nor parenthesis) in a method of a subclass calls the same method in the super-class (or its ancestors if the superclass does not define it) with all the parameter passed to the subclass method. So, here, you could have written simply super.

    Calling super() calls the superclass (or ancestors) method without any parameter (assuming this method accept no parameters...)

    Calling super(...) with any combination of parameters calls the superclass method, passing it the paramaters

    0 讨论(0)
  • 2020-12-30 06:11

    This looks like a better use for 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
    
    0 讨论(0)
提交回复
热议问题