Class: TwUbn::Validator

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

Overview

taiwan unified business number validator

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ubn) ⇒ Validator

Returns a new instance of Validator.



9
10
11
# File 'lib/tw_ubn.rb', line 9

def initialize(ubn)
  @ubn = ubn.to_s
end

Class Method Details

.call(*args) ⇒ Object



13
14
15
# File 'lib/tw_ubn.rb', line 13

def self.call(*args)
  new(*args).verify
end

Instance Method Details

#calculate_checksum(ubn_array) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/tw_ubn.rb', line 26

def calculate_checksum(ubn_array)
  first_result =
    ubn_array.map.with_index do |v, i|
      v * TwUbn::UBN_CALC_WEIGHT[i]
    end

  second_result =
    first_result.map { |v| (v / 10).floor + v % 10 }

  second_result.sum
end

#verifyObject



17
18
19
20
21
22
23
24
# File 'lib/tw_ubn.rb', line 17

def verify
  return false if (@ubn =~ /^\d{8}$/).nil?

  ubn_array = @ubn.chars.map(&:to_i)
  checksum = calculate_checksum(ubn_array)

  verify_checksum(checksum)
end

#verify_checksum(checksum) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/tw_ubn.rb', line 38

def verify_checksum(checksum)
  key = TwUbn::VERIFY_UBN_KEY
  use_special_verify = @ubn[6] == "7"

  if use_special_verify
    ((checksum - 10) % key).zero? ||
      ((checksum - 9) % key).zero?
  else
    (checksum % key).zero?
  end
end