5

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?

John Topley
  • 113,588
  • 46
  • 195
  • 237

2 Answers2

15

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

class X
  attr_accessor :favourites
  alias :favorites :favourites
end
Peter Cooper
  • 2,907
  • 28
  • 67
  • 87
  • Thanks Peter. Is there any reason to prefer `alias` to `alias_method`? – John Topley Jan 16 '10 at 19:05
  • 5
    `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 Jan 16 '10 at 19:09
  • 1
    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 Jan 16 '10 at 19:34
  • The `alias` keyword can be confusing or surprising. I would recommend to use `alias_method` http://stackoverflow.com/q/4763121/159721 – NARKOZ Mar 20 '14 at 12:17
8

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
  • 5,889
  • 2
  • 34
  • 48