Last active
January 25, 2018 18:25
-
-
Save michaelkoper/5007636 to your computer and use it in GitHub Desktop.
Handling with money in Mongoid
This file contains 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 Product | |
include Mongoid::Document | |
field :price, type: Money | |
end | |
Money.class_eval do | |
# Converts an object of this instance into a database friendly value. | |
def mongoize | |
[cents, currency.to_s] | |
end | |
class << self | |
# Get the object as it was stored in the database, and instantiate | |
# this custom class from it. | |
def demongoize(object) | |
cur = object[1] || Money.default_currency | |
Money.new(object[0], cur) | |
end | |
# Takes any possible object and converts it to how it would be | |
# stored in the database. | |
def mongoize(object) | |
case object | |
when Money | |
object.mongoize | |
else object | |
end | |
end | |
# Converts the object that was supplied to a criteria and converts it | |
# into a database friendly form. | |
def evolve(object) | |
case object | |
when Money then object.mongoize | |
else object | |
end | |
end | |
end | |
end | |
product = Product.new(:price => Money.new(1000, 'EUR')) | |
product.price.format | |
# => "€10.00" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment