Reputation: 10046
Aliasing methods in Ruby is relatively straight-forward. A contrived example:
class Person
def name
puts "Roger"
end
end
class User < Person
alias :old_name :name
def name
old_name
puts "Staubach"
end
end
In this case, running User.new.name
will output:
Roger
Staubach
That works as expected. However, I'm trying to alias a setter method, which is apparently not straight-forward:
class Person
def name=(whatever)
puts whatever
end
end
class User < Person
alias :old_name= :name=
def name=(whatever)
puts whatever
old_name = whatever
end
end
With this, calling User.new.name = "Roger"
will output:
Roger
It appears that the new aliased method gets called, but the original does not.
What is up with that?
ps - I know about super
and let's just say for the sake of brevity that I do not want to use it here
Upvotes: 2
Views: 1776
Reputation: 136
Does the alias have to be a setter?
class User < Person
alias :old_name :name=
def name=(whatever)
old_name whatever
end
end
Upvotes: -1
Reputation: 146073
You need self.old_name = whatever
, just plain old_name
is a local.
Upvotes: 1
Reputation: 3472
I don't think Ruby will recognize old_name = whatever
as a method call when it lacks an object reference. Try:
def name=(whatever)
puts whatever
self.old_name = whatever
end
instead (note the self.
)
Upvotes: 4