jerodsanto
jerodsanto

Reputation: 10046

Aliasing Setter Methods in Ruby

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

Answers (4)

Manish
Manish

Reputation: 111

Try this:

alias old_name= name=

Upvotes: 2

jmhobbs
jmhobbs

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

DigitalRoss
DigitalRoss

Reputation: 146073

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

Upvotes: 1

johusman
johusman

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

Related Questions