Skip to content

Instantly share code, notes, and snippets.

@darylenriquez
Last active July 22, 2017 13:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darylenriquez/8052fc6e505f6e010474ac82deffb7b5 to your computer and use it in GitHub Desktop.
Save darylenriquez/8052fc6e505f6e010474ac82deffb7b5 to your computer and use it in GitHub Desktop.
changing alias_method_chain to prepend
# 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