Class: SimpleForm::BankAccountNumber::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_form/bank_account_number/formatter.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fields, country) ⇒ Formatter

Returns a new instance of Formatter.



31
32
33
34
# File 'lib/simple_form/bank_account_number/formatter.rb', line 31

def initialize(fields, country)
  @fields = fields
  @country = country
end

Class Method Details

.formatted_bank_account_number(full_number, country) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/simple_form/bank_account_number/formatter.rb', line 13

def self.(full_number, country)
  full_number = full_number.to_s.dup
  format = number_format(country)

  fields = format.fetch(:parts).inject({}) do |hash, part|
    length = part.fetch(:format).source.scan(/\b\d}/).map(&:to_i).max
    field = full_number.slice!(0, length || full_number.length)

    hash.merge!(part.fetch(:label) => field)
  end

  unless full_number.empty?
    raise ArgumentError, "format does not match (#{full_number.length} extra digits)"
  end

  new(fields, country)
end

.number_format(country) ⇒ Object



7
8
9
10
11
# File 'lib/simple_form/bank_account_number/formatter.rb', line 7

def self.number_format(country)
  BankAccountNumber::COUNTRIES.fetch(
    country.upcase, BankAccountNumber::COUNTRIES[nil]
  )
end

Instance Method Details

#multiline?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/simple_form/bank_account_number/formatter.rb', line 52

def multiline?
  self.class.number_format(@country).fetch(:multiline)
end

#to_hObject



48
49
50
# File 'lib/simple_form/bank_account_number/formatter.rb', line 48

def to_h
  @fields
end

#to_s(value_separator: ": ", field_separator: "\n") ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/simple_form/bank_account_number/formatter.rb', line 36

def to_s(value_separator: ": ", field_separator: "\n")
  hash = if multiline?
    to_h
  else
    { "Account Number" => to_h.values.join("-") } # TODO: i18n
  end

  hash.map do |label, value|
    [label, value_separator, value].join
  end.join(field_separator)
end