What is the best way to create alias to attributes in Ruby?

后端 未结 3 1313
梦谈多话
梦谈多话 2021-01-17 08:12

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 c

相关标签:
3条回答
  • 2021-01-17 09:01

    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
    
    0 讨论(0)
  • 2021-01-17 09:06

    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
    
    0 讨论(0)
  • 2021-01-17 09:11

    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

    0 讨论(0)
提交回复
热议问题