Module: Cratchit::ClassMethods

Defined in:
lib/cratchit.rb

Instance Method Summary collapse

Instance Method Details

#money(method, opts = {}) ⇒ Object

Usage ==========================================================

From your ActiveRecord model, simply call the money method:

class Product < ActiveRecord::Base # Example usages money :price

money :price, :default => :zero

money :price, :default => 10.99

money :price, :default => Money.new(10, “EUR”)

money :price, :cents => “rate_in_cents”, :include_prefix => false

end



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

def money method, opts = {}
	options = { :include_prefix => true, :default => nil }
	options.merge! opts
		
options[:cents] ||= options[:include_prefix] ? method.to_s+'_cents' : 'cents'
options[:currency] ||= options[:include_prefix] ? method.to_s+'_currency' : 'currency'

default = case options[:default]
	when :zero then Money.new(0)
	when nil then nil
	else options[:default].to_money
end

composed_of method.to_sym,
	:class_name => "Money",
	:allow_nil => true,
	:mapping => [ [ options[:cents], 'cents' ], [ options[:currency], 'currency_as_string' ] ],
	:converter => Proc.new { |value| value.respond_to?(:to_money) ? (value.to_money unless value.blank?) : raise(ArgumentError, "Can't convert #{value.class} to Money") }

  after_initialize do
send "#{method}=".to_sym, default if send(method.to_sym).nil?
  end
end