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
.
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.
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
.
module Flanderizer
def hello
"#{super}-diddly"
end
end
class Person
def hello
"Hello"
end
end
# In ruby 2.0
Person.send(:prepend, Flanderizer)
# In ruby 2.1
Person.prepend(Flanderizer)
flanders = Person.new
puts 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.
flanders.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.