Class: Billy::Currency

Inherits:
Object
  • Object
show all
Includes:
ActionView::Helpers::NumberHelper
Defined in:
lib/billy/currency.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(iso_code) ⇒ Currency

Returns a new instance of Currency.



20
21
22
# File 'lib/billy/currency.rb', line 20

def initialize(iso_code)
  @attributes = self.class.all[iso_code.to_s.downcase]
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



5
6
7
# File 'lib/billy/currency.rb', line 5

def attributes
  @attributes
end

Class Method Details

.allObject



7
8
9
10
11
12
# File 'lib/billy/currency.rb', line 7

def self.all
  @currencies ||= begin
    path = Engine.root.join("config", "currencies", "iso.json")
    JSON.parse File.read(path)
  end
end

.format(amount, currency:, **options) ⇒ Object

Takes an amount (in cents) and currency and returns the formatted version for the currency



15
16
17
18
# File 'lib/billy/currency.rb', line 15

def self.format(amount, currency:, **options)
  currency ||= :usd
  new(currency).format_amount(amount, **options)
end

Instance Method Details

#delimiterObject



54
55
56
# File 'lib/billy/currency.rb', line 54

def delimiter
  attributes["delimiter"]
end

#formatObject



58
59
60
# File 'lib/billy/currency.rb', line 58

def format
  attributes["format"]
end

#format_amount(amount, **options) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/billy/currency.rb', line 24

def format_amount(amount, **options)
  number_to_currency(
    amount.to_i / subunit_to_unit.to_f,
    {
      precision: precision,
      unit: unit,
      separator: separator,
      delimiter: delimiter,
      format: format
    }.compact.merge(options)
  )
end

#precisionObject

Returns the precision to display

If 1, returns 0 If 100, returns 2 If 1000, returns 3



42
43
44
# File 'lib/billy/currency.rb', line 42

def precision
  subunit_to_unit.digits.count - 1
end

#separatorObject



50
51
52
# File 'lib/billy/currency.rb', line 50

def separator
  attributes["separator"]
end

#subunitObject



66
67
68
# File 'lib/billy/currency.rb', line 66

def subunit
  attributes["subunit"]
end

#subunit?Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/billy/currency.rb', line 62

def subunit?
  subunit.blank?
end

#subunit_to_unitObject



70
71
72
# File 'lib/billy/currency.rb', line 70

def subunit_to_unit
  attributes["subunit_to_unit"]
end

#unitObject



46
47
48
# File 'lib/billy/currency.rb', line 46

def unit
  attributes["unit"]
end