Hiasinho
Hiasinho

Reputation: 656

Overwrite methods of specific instance attributes

I have a class Invoice which inherits from ActiveRecord::Base. Invoice has an attribute called tax. What I want to do is, return a formatted string from the to_s method of the attribute tax that looks like 19,00 %.

Now, how do I overwrite the to_s method of a instance attribute?

I know, that I can do this in a view with number_with_precision and I18n enabled, but I want the functionality in a central position. Which is the the to_s method of the attribute.

Is this the right way to accomplish this behavior or is there another way of getting this done?

Upvotes: 1

Views: 121

Answers (1)

Mischa
Mischa

Reputation: 43298

You can't overwrite the to_s method of attributes. What you can do is create a method in your Invoice model called formatted_tax like this:

class Invoice < ActiveRecord::Base
  def formatted_tax
    # do your formatting on self.tax here
  end
end

Upvotes: 2

Related Questions