mirror of
https://github.com/hakanensari/frankfurter.git
synced 2024-11-21 18:42:29 +01:00
Implement Converter
The API is fairly simple in order to get straight to the goal, convert an amount from a currency to another. I used the proposal from #25 which is similar to the google currency tool.
This commit is contained in:
parent
77f9fedaca
commit
46dbb66b0f
32
lib/converter.rb
Normal file
32
lib/converter.rb
Normal file
@ -0,0 +1,32 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'bigdecimal'
|
||||
require 'quote'
|
||||
|
||||
class Converter
|
||||
attr_reader :to, :from
|
||||
|
||||
def initialize(params = {})
|
||||
@amount = params[:amount]
|
||||
@from = params[:from]
|
||||
@to = params[:to]
|
||||
end
|
||||
|
||||
# Converts an amount into a new currency
|
||||
# @param quote [Quote] the quote object
|
||||
# @return amount [BigDecimal] the converted amount
|
||||
def convert(quote = latest_quote)
|
||||
return amount if quote.base == to
|
||||
amount * quote.rates.fetch(to) { raise Quote::Invalid, 'Invalid to' }
|
||||
end
|
||||
|
||||
def amount
|
||||
BigDecimal(@amount.to_s)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def latest_quote
|
||||
@latest_quote ||= Quote.new(base: from)
|
||||
end
|
||||
end
|
45
spec/converter_spec.rb
Normal file
45
spec/converter_spec.rb
Normal file
@ -0,0 +1,45 @@
|
||||
require_relative 'helper'
|
||||
require 'converter'
|
||||
|
||||
describe Converter do
|
||||
let(:to) { 'USD' }
|
||||
let(:from) { 'EUR' }
|
||||
let(:amount) { '100.0' }
|
||||
|
||||
let(:converter) { Converter.new to: to, from: from, amount: amount }
|
||||
let(:quote) { Quote.new }
|
||||
|
||||
describe '#amount' do
|
||||
it 'casts to BigDecimal' do
|
||||
converter.amount.must_be_kind_of BigDecimal
|
||||
end
|
||||
end
|
||||
|
||||
describe '#convert' do
|
||||
it 'should return the amount' do
|
||||
quote.stub :base, to do
|
||||
converter.convert(quote).must_equal BigDecimal(amount)
|
||||
end
|
||||
end
|
||||
|
||||
it 'should use the rates to convert' do
|
||||
quote.stub :rates, Hash(to => 1.2) do
|
||||
converter.convert(quote).must_equal BigDecimal('120.0')
|
||||
end
|
||||
end
|
||||
|
||||
it 'should raise with invalid currency' do
|
||||
quote.stub :rates, Hash.new do
|
||||
-> { converter.convert(quote) }.must_raise Quote::Invalid, 'Invalid to'
|
||||
end
|
||||
end
|
||||
|
||||
it 'should use latest quote as default' do
|
||||
quote.stub :rates, Hash(to => 1.3) do
|
||||
converter.stub :latest_quote, quote do
|
||||
converter.convert.must_equal 130.0
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in New Issue
Block a user