Created
August 18, 2011 05:03
-
-
Save pda/1153327 to your computer and use it in GitHub Desktop.
ComposableOfMoney: currency attributes in ActiveRecord
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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