Module: HasMoney::ClassMethods
- Defined in:
- lib/has_money.rb
Instance Method Summary collapse
- #calculate_cents_from_dollars(dollars) ⇒ Object
- #calculate_cents_from_dollars_without_cents(dollars) ⇒ Object
- #calculate_dollars_from_cents(cents) ⇒ Object
- #calculate_dollars_without_cents_from_cents(cents) ⇒ Object
- #has_money(*attributes) ⇒ Object
Instance Method Details
#calculate_cents_from_dollars(dollars) ⇒ Object
39 40 41 42 43 44 45 46 47 |
# File 'lib/has_money.rb', line 39 def calculate_cents_from_dollars(dollars) return nil if dollars.nil? dollars = dollars.to_s.gsub(/[$,]/, "").strip dollars[0] = '0.' if dollars =~ /^\.\d{1,2}/ return nil unless dollars.match(/^-?\d+\.?(\d+)?$/) # xx.xxx (BigDecimal(dollars).round(2) * 100).to_i end |
#calculate_cents_from_dollars_without_cents(dollars) ⇒ Object
54 55 56 57 58 59 60 61 62 |
# File 'lib/has_money.rb', line 54 def calculate_cents_from_dollars_without_cents(dollars) return nil if dollars.nil? dollars = dollars.to_s.gsub(/[$,]/, "").strip dollars[0] = '0.' if dollars =~ /^\.\d{1,2}/ return nil unless dollars.match(/^-?\d+\.?(\d+)?$/) # xx.xxx (BigDecimal(dollars).round * 100).to_i end |
#calculate_dollars_from_cents(cents) ⇒ Object
34 35 36 37 |
# File 'lib/has_money.rb', line 34 def calculate_dollars_from_cents(cents) return nil if cents.nil? || cents == '' "%.2f" % (BigDecimal(cents.to_s) / 100).to_f end |
#calculate_dollars_without_cents_from_cents(cents) ⇒ Object
49 50 51 52 |
# File 'lib/has_money.rb', line 49 def calculate_dollars_without_cents_from_cents(cents) return nil if cents.nil? || cents == '' "%i" % (BigDecimal(cents.to_s) / 100).to_f.round end |
#has_money(*attributes) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/has_money.rb', line 11 def has_money(*attributes) attributes.each do |attribute| class_eval " def \#{attribute}_in_dollars\n self.class.calculate_dollars_from_cents(\#{attribute})\n end\n\n def \#{attribute}_in_dollars=(dollars)\n self.\#{attribute} = self.class.calculate_cents_from_dollars(dollars)\n end\n\n # Special dollars only formatting (no decimal place and rounded to the nearest dollar)\n def \#{attribute}_in_dollars_without_cents\n self.class.calculate_dollars_without_cents_from_cents(\#{attribute})\n end\n\n def \#{attribute}_in_dollars_without_cents=(dollars)\n self.\#{attribute} = self.class.calculate_cents_from_dollars_without_cents(dollars)\n end\n EOS\n end\nend\n" |