O'Reilly logo

Metaprogramming Ruby 2 by Paolo Perrotta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The Rise of alias_method_chain

In The Include-and-Extend Trick, I showed you a snippet of code from an old version of Rails…minus a few interesting lines. Here is the same code again, with those lines now visible and marked with arrows:

gems/activerecord-2.3.2/lib/active_record/validations.rb
 
module​ ActiveRecord
 
module​ Validations
 
 
def​ self.included(base)
 
base.extend ClassMethods
*
base.class_eval ​do
*
alias_method_chain :save, :validation
*
alias_method_chain :save!, :validation
*
end
 
 
# ...
 
 
end

When ActiveRecord::Base includes the Validations module, the marked lines reopen Base and call a method named alias_method_chain. Let me show you a quick example to explain what alias_method_chain does.

The Reason for alias_method_chain ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required