Alias ​​attr_reader in Ruby

Is it possible to use a method alias attr_readerin Ruby? I have a class with a property favouritesfor which I want to add an alias favoritesfor American users. What is this idiomatic Ruby way for this?

+3
source share
2 answers

attr_reader simply generates the appropriate instance methods. It:

class Foo
  attr_reader :bar
end

identical to:

class Foo
  def bar
    @bar
  end
end

therefore alias_method works as you expected so that:

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
+6
source

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

class X
  attr_accessor :favourites
  alias :favorites :favourites
end
+12
source

Source: https://habr.com/ru/post/1728755/


All Articles