Rails - format number as currency format in Getter

I am making a simple retail solution where there are prices in several different models. These prices contribute to the overall price . Imagine paying $ 0.30 more for choosing a valley for your yogurt.

When I set the field priceto

t.decimal   :price, precision:8, scale:2

The database is stored 6.50as 6.5. I know that in standard rails mode you call number_to_currency(price)to get the formatted value in the views. I need to programmatically call a field priceas well as a formatted string, i.e. $ 6.50 in several places that are not directly part of the presentation. In addition, my needs are simple (no currency conversion, etc.), I prefer the price to be fully formatted in the model without calling number_to_currency in the views again.

Is there a good way that I can change my price gain so that it always returns two decimal places with a dollar sign, i.e. 6.50 dollars when he called?

Thanks in advance.

UPDATE

Thanks to everyone.

Alex, , "" . , :

  def price_change=(val)
      write_attribute :price_change, val.to_s.gsub(/[\$]/,'').to_d
  end

  def price_change
    "$%.2f" % self[:price_change]
  end

.

2

Caveat Emptor. , , .

, , - , .

+5
4

, , :

def price
   "$%.2f" % self[:price]
end

, Rails

def price
   ActionController::Base.helpers.number_to_currency(self[:price])
end

. , !

+12

, , , . :

ActionController::Base.helpers.number_to_currency(6.5)   
#=> "$6.50"   

, .

def helpers
  ActionController::Base.helpers
end

"#{helpers.number_to_currency(6.5)}"

railscast

+2

Presenter, Draper (. this reailscast).

, .. formatted_price, (.. ActionView::Helpers::NumberHelper). rails, - , , .

+1

include ActionView::Helpers::NumberHelper

-1

All Articles