Module: ActsAsDecimal::ClassMethods
- Defined in:
- lib/acts_as_decimal/acts_as_decimal.rb
Instance Method Summary collapse
-
#acts_as_decimal(attr_name, options = {:decimals => 2}) ⇒ Object
Implements integer handling as floating numbers.
Instance Method Details
#acts_as_decimal(attr_name, options = {:decimals => 2}) ⇒ Object
Implements integer handling as floating numbers. Usage:
Inside a model with a price or amount field, simply put
acts_as_decimal field_name, :decimals => 2
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/acts_as_decimal/acts_as_decimal.rb', line 19 def acts_as_decimal(attr_name, = {:decimals => 2}) fields = [attr_name] unless attr_name.is_a? Array fields.each do |field| define_method "human_#{field}" do |*| ActiveSupport::Deprecation.warn("acts_as_decimal: The human helper has been deprecated. Please use #{field}.number_with_precision, directly in your views. More info: http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision") = .first || {:thousand_delimiters => true} return number_with_precision(self.send(field), :delimiter => ([:thousand_delimiters] ? '.' : ''), :separator => ',', :precision => 2) end define_method "#{field}" do if value = read_attribute("#{field}") value / BigDecimal('10').power("#{[:decimals]}".to_i).to_f end end define_method "#{field}=" do |decimalnum| value = unless decimalnum.nil? (BigDecimal.new(decimalnum.to_s) * BigDecimal('10').power("#{[:decimals]}".to_i)).to_i end write_attribute("#{field}", value || nil) end define_method "#{field}_raw" do read_attribute("#{field}") end define_method "#{field}_raw=" do |value| write_attribute("#{field}", value) end end end |