开发者

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 th开发者_运维技巧e sake of brevity that I do not want to use it here


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


Try this:

alias old_name= name=


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


Does the alias have to be a setter?

class User < Person
  alias :old_name :name=
  def name=(whatever)
    old_name whatever
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜