Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRYing Views in Rails (number_to_currency)

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?

like image 950
Gav Avatar asked Sep 09 '09 15:09

Gav


2 Answers

number_to_currency is a view helper, so it is not available in models.

You could save some key strokes by defining your own helper in application_helper.rb (so it is available to all views). Eg

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

Then call it in views:

quid(line_item.price)
like image 173
Larry K Avatar answered Sep 21 '22 00:09

Larry K


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 £.

like image 40
Josh Avatar answered Sep 21 '22 00:09

Josh