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 rest of them to the original update_attributes() method. The details:
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
The call to super.update_attributes(attr) raises an error:
undefined method `update_attributes' for true:TrueClass
... which makes me suspect I really don't understand the super keyword in Ruby. What am I missing? Specifically, how do I call the original update_attributes() method?
When you call super with no arguments, Ruby sends a message to the parent of the current object, asking it to invoke a method with the same name as where you called super from, along with the arguments that were passed to that method. On the other hand, when called with super() , it sends no arguments to the parent.
Ruby uses the super keyword to call the superclass implementation of the current method. Within the body of a method, calls to super acts just like a call to that original method. The search for a method body starts in the superclass of the object that was found to contain the original method.
The super keyword in Java is a reference variable that is used to refer parent class objects. The super() in Java is a reference variable that is used to refer parent class constructors. super can be used to call parent class' variables and methods. super() can be used to call parent class' constructors only.
In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With