Clean way to handle prices

Hi,

Currently I am storing my prices as cents. I have one major issue, it is
the way I convert this value into a decimal looking price. This is done
easily with to_f and *100).to_i, but it looks ugly and clutters my
controllers specially when updating the record. I tried with callbacks,
but it doesn’t do the trick if validation fails, as it returns the raw
values, i.e in cents.

I tried redefining price and price=, but it caused a stack too deep
problem with infinite self referential.

What’s the consensus on that? Use the Money gem? I expected to have a
nice rubyish solution to that problem.

Best regards,

Fernando,I suggest you look at
number_to_currency (ActionView::Helpers::NumberHelper) - APIdock.
Call the helper with value.to_f * / 100

James.

2009/3/22 Fernando P. [email protected]

james already mentioned the best way to do this, but if that doesn’t
match your requirements, just write your own helper-method. stuff like
that is not done inside the controller.

As someone else mentioned, wrapping this conversion to dollars makes
it a lot easier to manage.

The stack too deep problem in your overloading of price and price=
should be able to be solved by using the direct accesors like so:

def price
cents_to_dollars(read_attribute(:price))
end

def price=(value)
write_attribute(:price, dollars_from_cents(value))
end

or however you want to manually manage the accessors, just make sure
when overloading you use the read_attribute, and write_attribute,
because if you simply use the variable as normally, you will be
calling the same method you are defining, causing the stack too deep
error.

On Mar 22, 1:44 pm, Fernando P. [email protected]

or however you want to manually manage the accessors, just make sure
when overloading you use the read_attribute, and write_attribute

That’s exactly what I was looking for! I couldn’t find these methods in
railsbrain because they are private, therefore no documentation is
generated except if you read the very long text at ActiveRecord::Base.

Thank you very much.