2

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

jerodsanto
  • 9,726
  • 8
  • 29
  • 23

4 Answers4

4

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.)

johusman
  • 3,472
  • 1
  • 17
  • 11
  • Thanks, that works. I also realized that there is pretty much no reason that the aliased version has to be a setter, I can just pass the parameter directly to it and it'll work. – jerodsanto Feb 25 '11 at 22:46
  • 1
    See http://stackoverflow.com/questions/44715/why-do-ruby-setters-need-self-qualification-within-the-class – Josh Lee Feb 25 '11 at 22:49
2

Try this:

alias old_name= name=
Manish
  • 111
  • 4
1

You need self.old_name = whatever, just plain old_name is a local.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
-1

Does the alias have to be a setter?

class User < Person
  alias :old_name :name=
  def name=(whatever)
    old_name whatever
  end
end
jmhobbs
  • 116
  • 7