Guest User

Untitled

a guest
Jul 20th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. module PriceFields
  2. module ClassMethods
  3. def prices(*price_columns) # We assume "price_columns" to finish with "cents"
  4. price_columns.each do |price_name|
  5. col_name = "#{price_name}_cents".to_sym
  6. var_name = "#{price_name}_price".to_sym
  7. method_name = "#{var_name}_with_cast=".to_sym
  8.  
  9. self.composed_of var_name, :class_name => "Money", :mapping => [col_name, :cents]
  10.  
  11. define_method method_name do |value|
  12. case value
  13. when String
  14. self.send("#{var_name}_without_cast=", Money.new(price_string_to_cents(value)))
  15. else
  16. self.send("#{var_name}_without_cast=", value)
  17. end
  18. end
  19. self.alias_method_chain "#{var_name}=".to_sym, :cast
  20. end
  21. end
  22. end
  23.  
  24. module InstanceMethods
  25. def price_string_to_cents(value)
  26. (BigDecimal(value) * 100).to_i
  27. end
  28. end
  29.  
  30. def self.included(receiver)
  31. receiver.extend ClassMethods
  32. receiver.send :include, InstanceMethods
  33. end
  34. end
Add Comment
Please, Sign In to add comment