ruby-on-railsrubyaliasalias-method

Is it possible to alias to_s?


Instead of overriding to_s in my model I'd like to alias it to an existing method called full_name.

Both alias and alias_method don't seem to work as expected.

Using alias

class Person < ActiveRecord::Base

  # ... other model code.

  alias to_s full_name

  def full_name
     "#{first_name} #{last_name}"
  end
end

# In Terminal
> Person.last.to_s  #=> "#<Person:0x007fa5f8a81b50>"

Using alias_method

class Person < ActiveRecord::Base

  # ... other model code.

  alias_method :to_s, :full_name

  def full_name
     "#{first_name} #{last_name}"
  end
end

# In Terminal
> Person.last.to_s  #=> "#<Person:0x007fa5f8a81b50>"

Solution

  • Figured it out...

    alias and alias_method need to come after the method you are aliasing to.

    So both of the following work fine:

    Using alias

    class Person
      def full_name
         "#{first_name} #{last_name}"
      end
    
      alias to_s full_name
    end
    
    # In Terminal
    > Person.last.to_s  #=> "Don Draper"
    

    Using alias_method

    class Person
      def full_name
         "#{first_name} #{last_name}"
      end
    
      alias_method :to_s, :full_name
    end
    
    # In Terminal
    > Person.last.to_s  #=> "Don Draper"
    

    Hopefully that helps somebody else.