class Monee::Currency

class to manage currency code and rate, also the exchange

Constants

EMPTY_CURRENCY

error message to raise for empty string as currency

NO_CURRENCY

error message to raise with for uninitialized currencies

Attributes

code[R]
rate[R]

Public Class Methods

new(**options) click to toggle source

creates a currency object with code

@param options [Hash] code: 'USD' is one example @return [Currency]

# 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

Public Instance Methods

config() click to toggle source

@return [Config, NoConfig]

# File lib/monee/currency.rb, line 38
def config
  self.class.config
end
exchange(to_currency, cents) click to toggle source

exchanges the current currency to to_currency with cents and rate

@params to_currency [String] target currency to be converted to @params cents [Numeric] number of cents to be converted @raise [UndefinedCurrency] if to_currency is not in Config @return [Numeric] number of cents converted

# 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

Private Instance Methods

valid_currency?() click to toggle source

validation for currency object

@raise [EmptyCurrency] if currency is empty string @raise [UndefinedCurrency] if to_currency is not in Config

# File lib/monee/currency.rb, line 48
def valid_currency?
  raise EmptyCurrency, EMPTY_CURRENCY if code.empty?
  raise UndefinedCurrency, NO_CURRENCY unless config.exists?(code)
  true
end