To alias or alias_method?, that is the question
What do alias and alias_method do?
Both alias and alias_method allow you to use a synonym for a method name in Ruby.
What’s tricky?
Take a look at the source code below.
class Politician
def stump_speech
"I will grow the economy"
end
def self.add_slogan
alias :slogan :stump_speech
end
end</p>
<p>class Mayor < Politician
def stump_speech
"#{super} of this city"
end
add_slogan
end
class Politician2
def stump_speech
"I will grow the economy"
end
def self.add_slogan
alias_method :slogan, :stump_speech
end
end
class Mayor2 < Politician2
def stump_speech
"#{super} of this city"
end
add_slogan
end
p Politician.new.slogan
# => "I will grow the economy"
p Mayor.new.slogan
# => "I will grow the economy"
# The alias method "slogan" is not able to pick up on the method "stump_speech" defined in Mayor
# This is because alias refers specifically to the stump_speech method as defined in the original location, the Politician class
# This is because the "self" object is treated as the value of self at the time the source code was read
p Mayor2.new.slogan
# => "I will grow the economy of this city"
# The alias_method method "slogan" is able to pick up on the method "stump_speech" defined in Mayor2
# This is because alias_method refers to the value of self at runtime
The difference is basically this: alias_method refers to the value of self at runtime and alias refers to the value of self at the original point in the source code where it was defined. That is why in the above source code Mayor2 can have his own custom slogan but Mayor cannot.
As Ernie Miller points out, since alias_method refers to the value of self at runtime, it could literally be pointing at anything, which implies you better have really good test coverage to avoid unforseen bugs.
This was an interesting point as I had originally preferred alias_method since it seemed more flexible, but now Ernie has taught me to proceed with caution.