Is alias_method_chain synonymous with alias_method? Is alias_method_chain synonymous with alias_method? ruby ruby

Is alias_method_chain synonymous with alias_method?


No. 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, :methodalias_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  #=> Steveperson.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, :capitalizationend

Now, the old rename is called rename_without_capitalization, and rename_with_capitalization is rename. For example:

person.rename("bob smith")person.first_name  #=> Bobperson.last_name   #=> Smithperson.rename_without_capitalization("tom johnson")person.first_name  #=> tomperson.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.