Skip to content

Instantly share code, notes, and snippets.

@guilherme
Created October 1, 2012 23:13
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 guilherme/3815120 to your computer and use it in GitHub Desktop.
Save guilherme/3815120 to your computer and use it in GitHub Desktop.
money monkey patch
module ActiveRecord
class Base
def self.money_attributes(*attrs)
(attrs || []).each do |attr|
attr = attr.to_s
define_method attr do
read_attribute(attr).tap do |value|
value = value.to_money if value
end
end
define_method "#{attr}=" do |value|
value_string = value.to_s.strip
if value_string.blank?
super(nil)
else
if value_string.match(/\p{alpha}/)
super(value_string)
else
super(value_string.to_money.to_f)
end
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment