Rails 5 deprecates alias_method_chain

Neeraj Singh

Neeraj Singh

August 21, 2016

This blog is part of our  Rails 5 series.

Rails 5 has deprecated usage of alias_method_chain in favor of Ruby's built-in method Module#prepend.

What is alias_method_chain and when to use it

A lot of good articles have been written by some very smart people on the topic of "alias_method_chain". So we will not be attempting to describe it here.

Ernier Miller wrote When to use alias_method_chain more than five years ago but it is still worth a read.

Using Module#prepend to solve the problem

Ruby 2.0 introduced Module#prepend which allows us to insert a module before the class in the class ancestor hierarchy.

Let's try to solve the same problem using Module#prepend.

1module Flanderizer
2  def hello
3    "#{super}-diddly"
4  end
5end
6
7class Person
8  def hello
9    "Hello"
10  end
11end
12
13# In ruby 2.0
14Person.send(:prepend, Flanderizer)
15
16# In ruby 2.1
17Person.prepend(Flanderizer)
18
19flanders = Person.new
20puts flanders.hello #=> "Hello-diddly"

Now we are back to being nice to our neighbor which should make Ernie happy.

Let's see what the ancestors chain looks like.

1flanders.class.ancestors # => [Flanderizer, Person, Object, Kernel]

In Ruby 2.1 both Module#include and Module#prepend became a public method. In the above example we have shown both Ruby 2.0 and Ruby 2.1 versions.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.