22

What is the best way to create an alias to a instance atribute in Ruby (I'm not using rails or any ruby gem, just, Ruby).
For example given the class below, how can I create an alias to the :student_name attribute accessors?

class Student
  attr_accessor :student_name
  alias :name :student_name    #wrong
end

s = Student.new
s.student_name = "Jordan"
puts s.name  # --> Jordan
s.name = "Michael" # --> NoMethodError: undefined method `name=' for #<Student:0x572394> ...

Thank's guys!

3 Answers 3

34

add

alias :name :student_name    # not wrong, only for getter
alias :name= :student_name=  # add this for setter
alias :name? :student_name?  # add this for boolean
19

For Rails

alias_attribute new_name, old_name

Source http://api.rubyonrails.org/classes/ActiveModel/AttributeMethods/ClassMethods.html#method-i-alias_attribute

Use case: When you, most likely, want to change the attribute name without changing schema and without breaking existing functionality

2
  • 3
    The original question clearly stated "I'm not using rails" and this solution only works for those using Rails.
    – McFadden
    Commented May 6, 2020 at 15:49
  • This solution also has an error (or at least it is not clear). The correct code should use symbols: alias_attribute :new_name, :old_name
    – Vlad
    Commented Jul 23, 2021 at 15:18
14

As John points out, you need to alias both the reader and the writer. This being Ruby, it's quite easy to define your own alias method to handle this for you.

class Module
  def alias_attr(new_attr, original)
    alias_method(new_attr, original) if method_defined? original
    new_writer = "#{new_attr}="
    original_writer = "#{original}="
    alias_method(new_writer, original_writer) if method_defined? original_writer
  end
end
1
  • 3
    I'm just being picky here but I would prefer to call it alias_attr to be consistent with alias_method. This way both would be of the form alias_thingtoalias.
    – Venkat D.
    Commented Aug 2, 2013 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.