Class: StrictMoney::HistoricalAmount

Inherits:
Object
  • Object
show all
Defined in:
lib/strict_money/historical_amount.rb

Overview

A value object to describe one or more money amounts at a point in time when the exchange rate was known.

Constant Summary collapse

RedundantCurrencyError =

Raised when HistoricalAmount is instantiated with more than one amount of a given currency.

Class.new(StandardError)
WrongCurrencyError =

Raised when an method is called with another historical amount whose currencies are not the same.

Class.new(StandardError)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(amounts) ⇒ HistoricalAmount

Returns a new instance of HistoricalAmount.



9
10
11
12
13
14
# File 'lib/strict_money/historical_amount.rb', line 9

def initialize(amounts)
  @amounts = amounts
  if currencies != currencies.uniq
    raise RedundantCurrencyError, currencies
  end
end

Class Method Details

.zero(*currencies) ⇒ Object



5
6
7
# File 'lib/strict_money/historical_amount.rb', line 5

def self.zero(*currencies)
  new(currencies.uniq.map { |currency| Amount.new(0, currency) })
end

Instance Method Details

#+(addend) ⇒ Object

Raises:



32
33
34
35
36
37
38
# File 'lib/strict_money/historical_amount.rb', line 32

def +(addend)
  raise WrongCurrencyError unless addend.currencies == currencies
  new_amounts = @amounts.map { |amount|
    amount + addend.amount(amount.currency)
  }
  self.class.new(new_amounts)
end

#<=>(other) ⇒ Object



25
26
27
28
29
30
# File 'lib/strict_money/historical_amount.rb', line 25

def <=>(other)
  if other.is_a?(HistoricalAmount) && currencies == other.currencies
    currency = currencies.first
    as_float(currency) <=> other.as_float(currency)
  end
end

#amount(currency) ⇒ Object



54
55
56
# File 'lib/strict_money/historical_amount.rb', line 54

def amount(currency)
  @amounts.detect { |amount| amount.currency == currency }
end

#as_float(currency) ⇒ Object



40
41
42
# File 'lib/strict_money/historical_amount.rb', line 40

def as_float(currency)
  amount(currency).as_float(currency)
end

#as_json(_options = nil) ⇒ Object



44
45
46
47
48
# File 'lib/strict_money/historical_amount.rb', line 44

def as_json(_options = nil)
  currencies.each_with_object({}) { |currency, result|
    result[currency] = amount(currency).as_float(currency)
  }
end

#currenciesObject



50
51
52
# File 'lib/strict_money/historical_amount.rb', line 50

def currencies
  @amounts.map(&:currency).sort
end

#positive?Boolean

Returns:



58
59
60
# File 'lib/strict_money/historical_amount.rb', line 58

def positive?
  @amounts.all?(&:positive?)
end