Guest User

Untitled

a guest
May 24th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. module HasMoney
  2.  
  3. def self.included(base)
  4. base.extend ClassMethods
  5. end
  6.  
  7. module ClassMethods
  8.  
  9. #
  10. # has_money :default_price
  11. #
  12. # def default_price_in_dollars
  13. # end
  14. #
  15. # def default_price_in_dollars=(dollars)
  16. # end
  17.  
  18. def has_money(*attributes)
  19. attributes.each do |attribute|
  20. class_eval <<-EOS
  21. def #{attribute}_in_dollars
  22. self.class.calculate_dollars_from_cents(#{attribute})
  23. end
  24.  
  25. def #{attribute}_in_dollars=(dollars)
  26. self.#{attribute} = self.class.calculate_cents_from_dollars(dollars)
  27. end
  28. EOS
  29. end
  30. end
  31.  
  32. def calculate_dollars_from_cents(cents)
  33. return nil if cents.nil? || cents == ''
  34. cents.to_f / 100
  35. end
  36.  
  37. def calculate_cents_from_dollars(dollars)
  38. return nil if dollars.nil? || dollars == ''
  39. (dollars.gsub(/[^0]/).to_f * 100).round
  40. end
  41.  
  42. end
  43. end
  44.  
  45. # Inlcude in all AR Models
  46. ActiveRecord::Base.send :include, HasMoney
Add Comment
Please, Sign In to add comment