Skip to content

Instantly share code, notes, and snippets.

@gabrieljoelc
Created February 26, 2015 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrieljoelc/59e89f9909f0aedce483 to your computer and use it in GitHub Desktop.
Save gabrieljoelc/59e89f9909f0aedce483 to your computer and use it in GitHub Desktop.
Little module for define dynamic methods that automatically convert values from methods ending in `_cents` methods to `BigDecimal` dollars.
module Dollarable
def acts_as_dollarable
attribute_names.select { |m| m.ends_with?('_cents') }.each do |m|
define_method m.gsub(/_cents/, '') do
value = send(m)
return BigDecimal(0) if value.blank? || value.zero?
BigDecimal(value) / 100
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment