2

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>"
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245

1 Answers1

8

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.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
  • 1
    I was literally halfway through the question when I was like, "Riiiiiiiiight...". Figured I'd finish what I started. If it saves somebody 10 seconds, it's worth the post. – Joshua Pinter Apr 22 '14 at 16:43
  • 3
    The important thing to note here is the `alias_method` call takes effect with whatever methods are declared *at that point* of evaluation. This means you can alias a method you subsequently override, preserving the original behaviour without the original name. – tadman Apr 22 '14 at 17:05
  • @tadman Now that's a proper explanation, thanks for adding that comment. – Joshua Pinter Apr 22 '14 at 21:32
  • I have the same problem but want to alias an ActiveRecord model attribute, like first_name, so I don't have the definition beforehand :/ – MegaTux Oct 18 '16 at 13:14
  • @MegaTux I would have guessed that `alias_method` should work for that. Did you try it? – Joshua Pinter Oct 18 '16 at 13:49
  • 1
    @MegaTux Try `alias_attribute :new_column_name, :column_name_in_db` as per http://stackoverflow.com/questions/4014831/alias-for-column-names-in-rails – Joshua Pinter Oct 18 '16 at 13:50
  • 1
    alias_attribute worked, thx @JoshPinter ! ( alias_attribute :to_s, :name ) – MegaTux Nov 05 '16 at 15:20