If these two methods are simply synonyms, why do people go to the trouble of writing the additional characters "_chain
"?
views:
1079answers:
2No. alias_method
is a standard method from Ruby. alias_method_chain
is a Rails add-on designed to simplify the common action of aliasing the old method to a new name and then aliasing a new method to the original name. So, if for example you are creating a new version of the method
method with the new feature new_feature
, the following two code examples are equivalent:
alias_method :method_without_new_feature, :method
alias_method :method, :method_with_new_feature
and
alias_method_chain :method, :new_feature
EDIT
Here is a hypothetical example: suppose we had a Person class with a method rename
. All it does is take a string like "John Doe", split on the space, and assign parts to first_name and last_name. For example:
person.rename("Steve Jones")
person.first_name #=> Steve
person.last_name #=> Jones
Now we're having a problem. We keep getting new names that aren't capitalized properly. So we can write a new method rename_with_capitalization
and use alias_method_chain
to resolve this:
class Person
def rename_with_capitalization(name)
rename_without_capitalization(name)
self.first_name[0,1] = self.first_name[0,1].upcase
self.last_name[0,1] = self.last_name[0,1].upcase
end
alias_method_chain :rename, :capitalization
end
Now, the old rename
is called rename_without_capitalization
, and rename_with_capitalization
is rename
. For example:
person.rename("bob smith")
person.first_name #=> Bob
person.last_name #=> Smith
person.rename_without_capitalization("tom johnson")
person.first_name #=> tom
person.last_name #=> johnson
alias_method_chain
is worst way of doing method call interception. If you are looking for similar techniques, do not use it outside rails.