Overriding Methods in Ruby
If you are new to Ruby, you may bump into some confusion when overriding methods, especially when you still need to refer to the old or parent methods. Just to share some notes I have taken on overriding methods in Ruby.
You can override a method by either extending a class or by re-declaring an exisiting class with just the new methods.
Let’s dive into codes, Ruby codes speak a thousand words.
Overriding Parent Instance Method
This is the typical way in Object-Oriented programming, by extending a class.
class Parent
def call_method
'parent'
end
end
class Child < Parent
def call_method
super + '-child' #return: 'parent-child'
end
end
Overriding Parent Class Method
Class methods are a bit more confusing, because there are different ways to declare them. Well, welcome to ruby, there are a lot of magic here.
There are three ways to declare class methods:
class ClassName
def ClassName.method_1
...
end
def self.method_2
...
end
class << self
def method_3
...
end
def method_4
...
end
end
end
To override a class method:
class Parent
def self.call_method
'parent'
end
end
class Child < Parent
def self.call_method
superclass.call_method + '-child' #return: 'parent-child'
end
end
Overriding Method of Existing Class
To override a method in an existing class, you just have to re-declare the class with the new methods. If you need to call the old method in your new method, you first have to create an alias of for the old method. You can use either alias or alias_method. This is something that I dont’ see in Java, pretty cool.
Note that you don’t need to redeclare Parent extension. And also note the difference in declaration between alias and alias_method; alias is a reserved keyword in Ruby, while alias_method is just a function call.
class Child
alias old_call_method call_method
def call_method
old_call_method + '-new' #return 'parent-child-new'
end
end
class Child
alias_method :old_call_method, :call_method
def call_method
old_call_method + '-new' #return 'parent-child-new'
end
end
Or you can also do it this way:
class Child
alias_method :old_call_method, :call_method
alias_method :call_method, :new_call_method
def new_call_method
old_call_method + '-new' #return 'parent-child-new'
end
end
# If you are using RailsOnEdge, this is the shortcut
class Child
alias_method_chain :call_method, :extra
def call_method_with_extra
call_method_without_extra + '-new' #return 'parent-child-new'
end
end

Add Your Comment