Skip to content

Instantly share code, notes, and snippets.

@siannopollo
Created October 24, 2015 21:21
Show Gist options
  • Save siannopollo/e65e62f6cfd53a3bf871 to your computer and use it in GitHub Desktop.
Save siannopollo/e65e62f6cfd53a3bf871 to your computer and use it in GitHub Desktop.
Convenience methods for storing price-like columns as cents, to avoid floating point math!
module StoredAsCents
def stored_as_cents(*methods)
methods.each do |m|
define_method "#{m}=" do |value|
cents = (value.to_f * 100).round
write_attribute "#{m}_in_cents", cents
end
define_method m do
cents = read_attribute "#{m}_in_cents"
float_value = cents.to_i / 100.0
int_value = float_value.to_i
float_value == int_value ? int_value : float_value
end
define_method "#{m}_changed?" do
send "#{m}_in_cents_changed?"
end
define_method "#{m}?" do
send "#{m}_in_cents?"
end
end
end
end
ActiveRecord::Base.extend StoredAsCents
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment