Class: Jekyll::Unirate::Snapshot

Inherits:
Object
  • Object
show all
Defined in:
lib/jekyll/unirate/snapshot.rb

Overview

An immutable single-base rate snapshot. One HTTP call to UniRate fetches base->code rates; every cross-rate is derived from this snapshot on demand (‘rate(F,T) = base->T / base->F`), so the whole build shares one frozen view of the market and no per-pair caching can go stale.

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base:, rates:) ⇒ Snapshot

Returns a new instance of Snapshot.

Parameters:

  • base (String)

    base currency the rates are expressed against

  • rates (Hash{String=>BigDecimal})

    base->code rate map



23
24
25
26
27
# File 'lib/jekyll/unirate/snapshot.rb', line 23

def initialize(base:, rates:)
  @base = base.to_s.upcase
  @rates = rates.freeze
  freeze
end

Class Attribute Details

.currentObject

Returns the value of attribute current.



18
19
20
# File 'lib/jekyll/unirate/snapshot.rb', line 18

def current
  @current
end

Instance Attribute Details

#baseObject (readonly)

Returns the value of attribute base.



12
13
14
# File 'lib/jekyll/unirate/snapshot.rb', line 12

def base
  @base
end

#ratesObject (readonly)

Returns the value of attribute rates.



12
13
14
# File 'lib/jekyll/unirate/snapshot.rb', line 12

def rates
  @rates
end

Instance Method Details

#convert(amount, from, to) ⇒ Object

Convert amount from from to to as a BigDecimal, or nil if no rate is available for the pair.



51
52
53
54
55
56
# File 'lib/jekyll/unirate/snapshot.rb', line 51

def convert(amount, from, to)
  r = rate(from, to)
  return nil if r.nil?

  BigDecimal(amount.to_s) * r
end

#currenciesObject

All currency codes available in this snapshot (including the base), sorted — handy for ‘for c in … %` style template loops.



31
32
33
# File 'lib/jekyll/unirate/snapshot.rb', line 31

def currencies
  ([@base] + @rates.keys).uniq.sort
end

#rate(from, to) ⇒ Object

Cross-rate from from to to as a BigDecimal, or nil if either currency is absent from the snapshot.



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/jekyll/unirate/snapshot.rb', line 37

def rate(from, to)
  from = from.to_s.upcase
  to = to.to_s.upcase
  return BigDecimal(1) if from == to

  from_rate = base_rate(from)
  to_rate = base_rate(to)
  return nil if from_rate.nil? || to_rate.nil?

  to_rate / from_rate
end