Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module PriceFields
- module ClassMethods
- def prices(*price_columns) # We assume "price_columns" to finish with "cents"
- price_columns.each do |price_name|
- col_name = "#{price_name}_cents".to_sym
- var_name = "#{price_name}_price".to_sym
- method_name = "#{var_name}_with_cast=".to_sym
- self.composed_of var_name, :class_name => "Money", :mapping => [col_name, :cents]
- define_method method_name do |value|
- case value
- when String
- self.send("#{var_name}_without_cast=", Money.new(price_string_to_cents(value)))
- else
- self.send("#{var_name}_without_cast=", value)
- end
- end
- self.alias_method_chain "#{var_name}=".to_sym, :cast
- end
- end
- end
- module InstanceMethods
- def price_string_to_cents(value)
- (BigDecimal(value) * 100).to_i
- end
- end
- def self.included(receiver)
- receiver.extend ClassMethods
- receiver.send :include, InstanceMethods
- end
- end
Add Comment
Please, Sign In to add comment