Module: ActiveRecord::Acts::Money::ClassMethods

Defined in:
lib/bd_money/rails.rb

Instance Method Summary collapse

Instance Method Details

#money(*names) ⇒ Object

Pass list of fields you want to use as Money. You can also pass a hash in the end to indicate your preferences for :precision and :round_mode.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/bd_money/rails.rb', line 32

def money(*names)
  options = names.extract_options!
  names.each do |name|
    if options[:precision]
      this_precision = options[:precision]
    else
      db_column      = columns.select { |x| x.name == name.to_s }.first
      this_precision = (db_column && db_column.respond_to?(:scale)) ? db_column.scale : nil
    end
    define_method "#{name}=" do |value|
      if value.present?
        self[name] = ::Money.new(value, this_precision, options[:round_mode], options[:format]).round.amount
      else
        self[name] = nil
      end
    end
    define_method "#{name}" do
      return nil unless self[name].present?
      ::Money.new self[name], this_precision, options[:round_mode], options[:format]
    end
  end
end