Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias attr_reader in Ruby

Tags:

ruby

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?

like image 848
John Topley Avatar asked Nov 28 '22 20:11

John Topley


2 Answers

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

class X
  attr_accessor :favourites
  alias :favorites :favourites
end
like image 85
Peter Cooper Avatar answered Dec 26 '22 00:12

Peter Cooper


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
like image 28
levinalex Avatar answered Dec 26 '22 00:12

levinalex