开发者

Alias attr_reader in Ruby

Is it possible to alias an attr_reader method in Ruby? I have a class with a favourit开发者_Python百科es property that I want to alias to favorites for American users. What's the idiomatic Ruby way to do this?


Yes, you can just use the alias method. A very scrappy example:

class X
  attr_accessor :favourites
  alias :favorites :favourites
end


attr_reader simply generates appropriate instance methods. This:

class Foo
  attr_reader :bar
end

is identical to:

class Foo
  def bar
    @bar
  end
end

therefore, alias_method works as you'd expect it to:

class Foo
  attr_reader :favourites
  alias_method :favorites, :favourites

  # and if you also need to provide writers
  attr_writer :favourites
  alias_method :favorites=, :favourites=
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜