Skip to content

Instantly share code, notes, and snippets.

@pda
Created August 18, 2011 05:03
Show Gist options
  • Save pda/1153327 to your computer and use it in GitHub Desktop.
Save pda/1153327 to your computer and use it in GitHub Desktop.
ComposableOfMoney: currency attributes in ActiveRecord
##
# Aggregation
# http://ar.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html
module ComposableOfMoney
extend ActiveSupport::Concern
included do
def self.composed_of_money(attr)
composed_of attr,
:class_name => "Money",
:mapping => [["#{attr}_cents", "cents"]],
:constructor => Proc.new { |cents|
Money.new(cents || 0, Money.default_currency) },
:converter => Proc.new { |value|
raise "Can't convert #{value.class} to Money" unless value.respond_to?(:to_money)
value.to_money }
end
end
end
class Example < ActiveRecord::Base
include ComposableOfMoney
composed_of_money :price
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment