Class: CurrencyNumberal::Currency

Inherits:
Numeric
  • Object
show all
Defined in:
lib/currency_numberal.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(number, code) ⇒ Currency

rubocop:disable Lint/MissingSuper



21
22
23
24
# File 'lib/currency_numberal.rb', line 21

def initialize(number, code)
  @number = number
  @code = code
end

Instance Attribute Details

#codeObject

Returns the value of attribute code.



18
19
20
# File 'lib/currency_numberal.rb', line 18

def code
  @code
end

#numberObject

Returns the value of attribute number.



18
19
20
# File 'lib/currency_numberal.rb', line 18

def number
  @number
end

Instance Method Details

#*(other) ⇒ Object

Raises:



72
73
74
75
76
# File 'lib/currency_numberal.rb', line 72

def *(other)
  raise Error, 'Invalid number' unless other.is_a?(Numeric)

  self.class.new(@number.to_f * other, @code)
end

#+(other) ⇒ Object



64
65
66
# File 'lib/currency_numberal.rb', line 64

def +(other)
  self.class.new(@number + other.send(@code).number, @code)
end

#-(other) ⇒ Object



68
69
70
# File 'lib/currency_numberal.rb', line 68

def -(other)
  self.class.new(@number - other.send(@code).number, @code)
end

#/(other) ⇒ Object

Raises:



78
79
80
81
82
# File 'lib/currency_numberal.rb', line 78

def /(other)
  raise Error, 'Invalid number' unless other.is_a?(Numeric)

  self.class.new(@number.to_f / other, @code)
end

#<=>(other) ⇒ Object



84
85
86
# File 'lib/currency_numberal.rb', line 84

def <=>(other)
  base <=> other.base
end

#baseObject



43
44
45
# File 'lib/currency_numberal.rb', line 43

def base
  @number.to_f / CurrencyNumberal::CURRENCIES[@code][:base]
end

#coerce(other) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/currency_numberal.rb', line 53

def coerce(other)
  case other
  when Float
    [self.class.new(other, @code), self]
  when Integer
    [self.class.new(other, @code), self]
  else
    [self.class.new(other.to_f, @code), self]
  end
end

#symbolObject

rubocop:enable Lint/MissingSuper



27
28
29
# File 'lib/currency_numberal.rb', line 27

def symbol
  CurrencyNumberal::CURRENCIES[@code][:symbol]
end

#to_fObject



35
36
37
# File 'lib/currency_numberal.rb', line 35

def to_f
  @number.to_f
end

#to_iObject



39
40
41
# File 'lib/currency_numberal.rb', line 39

def to_i
  @number.to_i
end

#to_sObject



31
32
33
# File 'lib/currency_numberal.rb', line 31

def to_s
  "#{@number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse} #{symbol}"
end