Economy
High performance multicurrency money for rails.
Why
I did this gem to:
- Keep rates cached in redis for optimal performance and sync between instances.
- Have an out of the box working rates service.
- Be able to make sql queries without the need to convert integers into decimals.
- Share a common currency column for multiple money fields if a need it.
- Avoid the need to manually format the string representation in views.
Install
Put this line in your Gemfile:
gem 'economy'
Then bundle:
$ bundle
To install Redis you can use homebrew:
$ brew install redis
Configuration
Generate the configuration file:
$ bundle exec rails g economy:install
Set the global settings:
Economy.configure do |config|
config.rates = :yahoo
config.default_currency = 'USD'
config.add_currency(
iso_code: 'USD',
iso_number: 840,
symbol: 'U$S',
decimals: 2
)
config.add_currency(
iso_code: 'UYU',
iso_number: 858,
symbol: '$U',
decimals: 2
)
end
NOTE: You may want to personalize the generated config/redis.yml.
Usage
Definitions
Add the money columns to your tables:
class AddPriceToProducts < ActiveRecord::Migration
def change
add_column :products, :price, :decimal, precision: 24, scale: 6
add_column :products, :currency, :string, limit: 3 # Or :price_currency
end
end
Define the money field in your models:
class Product < ActiveRecord::Base
monetize :price
end
Attributes
If you want to assign values, everything continuos working the same:
product.price = 20.00
product.currency = 'USD'
Arithmetics are intuitive:
product.price * 2 # => U$S 40
product.price / 2 # => U$S 10
product.price + Economy::Money.new(10, 'USD') # => U$S 30
product.price - Economy::Money.new(10, 'USD') # => U$S 10
To exchange to another currency:
product.price.exchange_to 'UYU'
The formatting method is to_s, it uses active support, so there is no need to call a helper in your views:
<%= product.price %>
Rates
You can use rake task:
$ bundle exec rake economy:update_rates
Or the plain method:
Economy.update_rates
NOTE: You probably want to put the rake task into a cronjob.
Credits
This gem is maintained and funded by mmontossi.
License
It is free software, and may be redistributed under the terms specified in the MIT-LICENSE file.