DigitalOpera::Banker
JD Hendrickson edited this page Nov 12, 2013
·
1 revision
The Banker is a Concern that we use to handle managing the conversion of dollars to cents and back.
# app/models/order.rb
class Order
include Mongoid::Document
include Mongoid::Timestamps
include DigitalOpera::Banker
## Define our currency fields
currency_fields :total
## Fields -----------------------------------
field :total_in_cents, type: Integer, default: 0
end
The Banker Concern gives you the class method currency_fields
which accepts a list of all currency fields in your model. The convention assumes that your currency fields in the database are stored in cents and named accordingly. So if we have a total
attribute, the Banker will look for a field named total_in_cents
to exist in your model.
# Using the class described above we can set the value using either of the banker controlled fields
order = Order.first
order.total_in_cents = 1000
puts order.total
# => "10.00"
order.total = "49.99"
puts order.total_in_cents
# => 4999
There isn't anything too special about this guy, so it "should" work pretty well regardless of your ORM, but it has been tested using both ActiveRecord and Mongoid.