Class: Monee::Currency

Inherits:
Object
  • Object
show all
Extended by:
Configurable
Defined in:
lib/monee/currency.rb

Overview

class to manage currency code and rate, also the exchange

Constant Summary collapse

NO_CURRENCY =

error message to raise with for uninitialized currencies

'This currency\'s conversion rate is not configured,
please use Monee::Money.conversion_rates'.freeze
EMPTY_CURRENCY =

error message to raise for empty string as currency

'Currency cannot to empty!'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Configurable

actual_config, configure, null_config?

Constructor Details

#initialize(**options) ⇒ Currency

creates a currency object with code

Parameters:

  • options (Hash)

    code: ‘USD’ is one example



20
21
22
23
24
# File 'lib/monee/currency.rb', line 20

def initialize(**options)
  options = options.compact
  @code = options[:code]
  @rate = config.fetch_rate(@code) if valid_currency?
end

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



14
15
16
# File 'lib/monee/currency.rb', line 14

def code
  @code
end

#rateObject (readonly)

Returns the value of attribute rate.



14
15
16
# File 'lib/monee/currency.rb', line 14

def rate
  @rate
end

Instance Method Details

#configConfig, NoConfig

Returns:



38
39
40
# File 'lib/monee/currency.rb', line 38

def config
  self.class.config
end

#exchange(to_currency, cents) ⇒ Numeric

exchanges the current currency to to_currency with cents and rate

Returns:

  • (Numeric)

    number of cents converted

Raises:



32
33
34
35
# File 'lib/monee/currency.rb', line 32

def exchange(to_currency, cents)
  raise UndefinedCurrency, NO_CURRENCY unless config.exists?(to_currency)
  (cents / rate) * config.fetch_rate(to_currency)
end