DRYing Views in Rails (number_to_currency)

Gav picture Gav · Sep 9, 2009 · Viewed 9.4k times · Source

I have code similar to:

number_to_currency(line_item.price, :unit => "£")

littering my views in various models. Since my application deals only in GBP (£), should I not move this into each of my models so that line_item.price returns the string as it should be (i.e. number_to_currency(line_item.price, :unit => "£") and line_item.price are the same. I'm thinking that to do this I should:

def price
 number_to_currency(self.price, :unit => "£")
end

but this doesn't work. If price is already defined in the model, then Rails reports 'stack level too deep', when I change def price to def amount, then it complains that number_to_currency is not defined?

Answer

Josh picture Josh · Dec 14, 2010

If you want to change the default for your whole application, you can edit config/locales/en.yml

Mine looks like this:

# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
"en":
  number:
    currency:
        format:
            format: "%u%n"
            unit: "£"
            # These three are to override number.format and are optional
            separator: "."
            delimiter: ","
            precision: 2

Everything except the unit is optional and will fall back to the default, but I put it in so I know what values I can change. you could also use the £ sign instead of £.