ruby - How to simplify my Rails money converter module? -
just out of curiosity:
is there way simplify file this:
module converter def hourly_rate hourly_rate_in_cents.to_d / 100 if hourly_rate_in_cents end def hourly_rate=(number) self.hourly_rate_in_cents = number.to_d * 100 if number.present? end def price price_in_cents.to_d / 100 if price_in_cents end def price=(number) self.price_in_cents = number.to_d * 100 if number.present? end def amount amount_in_cents.to_d / 100 if amount_in_cents end def amount=(number) self.amount_in_cents = number.to_d * 100 if number.present? end end
i using these function because need store money related values integers
in database, don't repitition in code.
you this
module converter def self.def_converter(name) define_method(name) value_in_cents = send("#{name}_in_cents") value_in_cents.to_d / 100 if value_in_cents.present? end define_method("#{name}=") |number| send("#{name}_in_cents=", number.to_d * 100) if number.present? end end def_converter(:hourly_rate) def_converter(:price) def_converter(:amount) end
Comments
Post a Comment