Module: Priceable

Defined in:
lib/priceable.rb,
lib/priceable/version.rb

Constant Summary collapse

SUFFIXES =
["_in_cents", "_in_pennies", "_as_integer"].freeze
VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#priceable(*price_fields) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/priceable.rb', line 8

def priceable(*price_fields)
  price_fields.each do |price_field|
    suffix = SUFFIXES.detect { |suffix| attribute_method? "#{price_field}#{suffix}" }
    raise ArgumentError, "Unable to find valid database field for `#{price_field}'" unless suffix
    
    define_method price_field do
      unless send("#{price_field}#{suffix}").nil?
        send("#{price_field}#{suffix}") / 100.0
      else
        0.0
      end
    end
    
    define_method "#{price_field}=" do |new_price|
      send("#{price_field}#{suffix}=", (new_price.to_f * 100).round)
    end
  end
end