RubyMoney/money

Augment currency exchange APIs to support historical rates

Closed this issue · 1 comments

First of all: I love this gem. I've used it in nearly ever Rails project I've worked on. Thank you to all the contributors!

One use-case I've run into several times that requires cumbersome workarounds is converting currencies for a particular date. The current API is able to represent USD:CAD, but it's not able to represent today's USD:CAD rate versus yesterday's USD:CAD rate.

The money-historical-bank attempts to solve this, but I think it could be solved elegantly in the money gem in a (mostly) backwards compatible way by adding an optional date: (or perhaps timestamp:) parameter to the methods involved in currency exchange:

Money.add_rate("USD", "CAD", 1.25) # Today's rate
Money.add_rate("USD", "CAD", 1.30, date: 1.day.ago) # Yesterday's rate

Money.new(100_00, "USD").exchange_to("CAD") # => Money.new(12500, "CAD")
Money.new(100_00, "USD").exchange_to("CAD", date: 1.day.ago) # => Money.new(13000, "CAD")

Each store would be responsible for implementation. For example, the store I'm using uses Redis and the Rails cache to read/write a hash of rates using the cache key "exchange-rates/2023-07-02".

It might require a major version bump because existing store implementations would raise an ArgumentError error because of the new date: parameter.

If there's interest in something like this, I'm happy to help out with the discussion & implementation.

would love to see a PR to have this considered.