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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With