Class: TaiwanValidator::UbnValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/taiwan_validator/ubn_validator.rb

Constant Summary collapse

MULTIPLIER =
[1,2,1,2,1,2,4,1].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.valid?(ubn) ⇒ Boolean

Returns:

  • (Boolean)


5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/taiwan_validator/ubn_validator.rb', line 5

def valid?(ubn)
  ubn = ubn.to_s
  return false unless ubn.match?(/\A\d{8}\z/)

  digits = ubn.chars.map(&:to_i)
  results = digits.zip(MULTIPLIER).map do |op1, op2|
    digit = op1 * op2
    digit = digit.to_s.chars.map(&:to_i).reduce(&:+) if number_digits(digit) == 2
    digit
  end.inject(&:+)

  results % 10 == 0 || (ubn[6] == "7" && (results + 1) % 10 == 0)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



26
27
28
29
30
# File 'lib/taiwan_validator/ubn_validator.rb', line 26

def validate_each(record, attribute, value)
  unless self.class.valid?(value)
    record.errors.add(attribute, options[:message] || :invalid)
  end
end