Overriding getters and setters

I’m trying to override getters and setters to convert currency figures
into integers and vice-versa.

I add this to my model:

def unit_price
@unit_price
end

def unit_price=(price)
@unit_price = price
end

And even this basic override doesn’t work. It gives me this error:

ArgumentError (comparison of String with 0 failed):
/app/models/product_price.rb:19:in <=' /app/models/product_price.rb:19:invalidate’

if I change the unit_price setter to this:

@unit_price = price.to_i

it completely ignores the entered values. Doesn’t give any error, but
updates the row with the old data.

What am I doing wrong here?

Matt R. wrote:

What am I doing wrong here?

Ahh… I had a custom validation method that was throwing the error. I
think I’ve got it fixed now.

You may be interested in the Money gem here’s a dodgy link to the docs
http://gemjack.com/gems/money-1.7.1/index.html.
Anyway overriding ActiveRecord accessors is not exactly the same than
rewriting generic ruby accessors.

try something like this

def unit_price=(price)
write_attribute :unit_price, price.to_i
end

unknown wrote:

You may be interested in the Money gem here’s a dodgy link to the docs
http://gemjack.com/gems/money-1.7.1/index.html.
Anyway overriding ActiveRecord accessors is not exactly the same than
rewriting generic ruby accessors.

try something like this

def unit_price=(price)
write_attribute :unit_price, price.to_i
end

Nice. I’ll definitely check out that money gem. I guess that makes
sense about active record accessors. Thanks!

Matt