Forum: Ruby on Rails Clean way to handle prices

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Fernando P. (Guest)
on 2009-03-22 02:44

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,
James Cowlishaw (Guest)
on 2009-03-22 09:39
(Received via mailing list)
Fernando,I suggest you look at
Call the helper with value.to_f * / 100


2009/3/22 Fernando P. <removed_email_address@domain.invalid>
MaD (Guest)
on 2009-03-22 10:22
(Received via mailing list)
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.
Jeremy Olliver (Guest)
on 2009-03-22 11:17
(Received via mailing list)
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

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

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

On Mar 22, 1:44 pm, Fernando P. <removed_email_address@domain.invalid>
Fernando P. (Guest)
on 2009-03-22 15:07
> 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.
This topic is locked and can not be replied to.