Last active
July 22, 2017 13:21
-
-
Save darylenriquez/8052fc6e505f6e010474ac82deffb7b5 to your computer and use it in GitHub Desktop.
changing alias_method_chain to prepend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A simplified explanation for moving alias_method_chain to prepend | |
# Sample class | |
class Note | |
def show_id | |
puts self.object_id | |
end | |
end | |
# using alias_method_chain: | |
class Note | |
def show_id_with_name | |
print "#{self.class.name}: " | |
show_id_without_name | |
end | |
alias_method_chain :show_id, :name | |
end | |
# when using alias_method_chain, it adds a new method :show_id_without_name which is actually the original :name method | |
# it essentially renames the :name method to :show_id_without_name | |
# afterwards, it redefines the :name method with the method :show_id_with_name | |
# it essentiall renames :show_id_with_name with :name | |
# so everytime you call :name, :show_id_with_name is actually executed | |
# when you call :show_id_without_name, the original :name method is executed | |
# using prepend | |
module Verbose | |
def show_id | |
print "#{self.class.name}: " | |
super | |
end | |
end | |
Note.prepend(Verbose) | |
# prepend adds the module to the ancestors tree, putting that method first so the methods of the module will take precedence | |
# that enables calling super which will execute the original :show_id method | |
# or rather executes the next :show_id in the method lookup chain |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment