tags:

views:

227

answers:

2

Is it possible to alias an attr_reader method in Ruby? I have a class with a favourites property that I want to alias to favorites for American users. What's the idiomatic Ruby way to do this?

+9  A: 

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

class X
  attr_accessor :favourites
  alias :favorites :favourites
end
Peter Cooper
Yet still a great one!
Doug Neiner
Thanks Peter. Is there any reason to prefer `alias` to `alias_method`?
John Topley
`alias` is a keyword and therefore a little more low-level than `alias_method`. `alias` will resolve methods statically, while `alias_method` does depend on the current `self`. See http://www.ruby-forum.com/topic/135598#604485 (but for your use case, it makes no difference)
levinalex
For this example is pretty much the same thing. alias and alias_method within a class defenition do the same thing given that the methods you are trying to alias are instance methods. If you use alias outside a class definition, lets say inside a instance_eval, your 'aliasing' a method of self, thus creating a singleton method for that object. If self happens to be a class then you're 'aliasing' a instance method to a singleton method of the class, which as you might have guess is in fact a class method.
pgmura
+4  A: 

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
levinalex