Class: Philiprehberger::Money::ExchangeRate

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/money/exchange_rate.rb

Overview

Thread-safe exchange rate store for currency conversion.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeExchangeRate

Returns a new instance of ExchangeRate.



17
18
19
20
# File 'lib/philiprehberger/money/exchange_rate.rb', line 17

def initialize
  @rates = {}
  @mutex = Mutex.new
end

Class Method Details

.reset!Object



12
13
14
# File 'lib/philiprehberger/money/exchange_rate.rb', line 12

def reset!
  @store = new
end

.storeObject



8
9
10
# File 'lib/philiprehberger/money/exchange_rate.rb', line 8

def store
  @store ||= new
end

Instance Method Details

#clearObject



49
50
51
52
# File 'lib/philiprehberger/money/exchange_rate.rb', line 49

def clear
  @mutex.synchronize { @rates.clear }
  self
end

#get(from, to) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/philiprehberger/money/exchange_rate.rb', line 33

def get(from, to)
  from_sym = from.to_s.upcase.to_sym
  to_sym = to.to_s.upcase.to_sym
  return BigDecimal('1') if from_sym == to_sym

  @mutex.synchronize do
    rate = @rates[[from_sym, to_sym]]
    return rate if rate

    inverse = @rates[[to_sym, from_sym]]
    return BigDecimal('1') / inverse if inverse

    raise Money::Error, "No exchange rate found for #{from_sym} -> #{to_sym}"
  end
end

#rates_countObject



54
55
56
# File 'lib/philiprehberger/money/exchange_rate.rb', line 54

def rates_count
  @mutex.synchronize { @rates.size }
end

#set(from, to, rate) ⇒ Object

Raises:



22
23
24
25
26
27
28
29
30
31
# File 'lib/philiprehberger/money/exchange_rate.rb', line 22

def set(from, to, rate)
  from_sym = from.to_s.upcase.to_sym
  to_sym = to.to_s.upcase.to_sym
  raise Money::Error, 'Rate must be positive' unless rate.is_a?(Numeric) && rate.positive?

  @mutex.synchronize do
    @rates[[from_sym, to_sym]] = BigDecimal(rate.to_s)
  end
  self
end