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?
views:
227answers:
2
                +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
                   2010-01-16 18:50:15
                
              Yet still a great one!
                  Doug Neiner
                   2010-01-16 18:50:58
                Thanks Peter. Is there any reason to prefer `alias` to `alias_method`?
                  John Topley
                   2010-01-16 19:05:29
                `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
                   2010-01-16 19:09:30
                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
                   2010-01-16 19:34:28
                
                +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
                   2010-01-16 18:53:42