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
18
# File 'lib/taiwan_validator/ubn_validator.rb', line 5

def valid?(ubn)
  ubn = ubn.to_s
  return false if ubn.size != 8 || (ubn =~ /\A\d+\Z/).nil?

  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 = digit.to_s.chars.last.to_i if number_digits(digit) == 2
    digit
  end.inject(&:+)

  results % 10 == 0
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



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

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