Class: Pay::Currency

Inherits:
Object
  • Object
show all
Includes:
ActionView::Helpers::NumberHelper
Defined in:
lib/pay/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/pay/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/pay/currency.rb', line 5

def attributes
  @attributes
end

Class Method Details

.allObject



7
8
9
10
11
12
# File 'lib/pay/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/pay/currency.rb', line 15

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

Instance Method Details

#additional_precision(amount) ⇒ Object

If amount is 0.8, we want to display $0.008



47
48
49
50
# File 'lib/pay/currency.rb', line 47

def additional_precision(amount)
  _, decimals = amount.to_s.split(".")
  decimals&.length || 0
end

#delimiterObject



60
61
62
# File 'lib/pay/currency.rb', line 60

def delimiter
  attributes["delimiter"]
end

#formatObject



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

def format
  attributes["format"]
end

#format_amount(amount, **options) ⇒ Object



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

def format_amount(amount, **options)
  number_to_currency(
    amount.to_f / subunit_to_unit.to_f,
    {
      precision: precision + additional_precision(amount),
      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/pay/currency.rb', line 42

def precision
  subunit_to_unit.digits.count - 1
end

#separatorObject



56
57
58
# File 'lib/pay/currency.rb', line 56

def separator
  attributes["separator"]
end

#subunitObject



72
73
74
# File 'lib/pay/currency.rb', line 72

def subunit
  attributes["subunit"]
end

#subunit?Boolean

Returns:

  • (Boolean)


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

def subunit?
  subunit.blank?
end

#subunit_to_unitObject



76
77
78
# File 'lib/pay/currency.rb', line 76

def subunit_to_unit
  attributes["subunit_to_unit"]
end

#unitObject



52
53
54
# File 'lib/pay/currency.rb', line 52

def unit
  attributes["unit"]
end