class Dixon::Validators::Taiwan

Constants

INVALID_MESSAGE
LETTER_ISSUED_BY
LETTER_NUMBERS
RULE_NUMBERS

Public Instance Methods

checks(id) click to toggle source

Check if a given ID is valid. ‘id` must be a string, case is insensitive. First convert ID into all numbers, then multiply to RULE_NUMBERS element by element. Sum up and take a 10 modulo then check if remainder is 0. If it’s, return true, false otherwise.

# File lib/dixon/validators/taiwan.rb, line 46
def checks(id)
  # "F127337575" => [1, 5, 1, 2, 7, 3, 3, 7, 5, 7, 5]
  converted = convert id.to_s
  #    [1,  5,  1,  2,  7,  3,  3,  7,  5,  7, 5]
  #  * [1,  9,  8,  7,  6,  5,  4,  3,  2,  1, 1]
  #  --------------------------------------------
  # sum 1, 45,  8, 14, 43, 15, 12, 21, 10,  7, 5
  # => 180
  # 180 mod 10, is the remainder equal to zero? If so, return true.
  return (mapcar(-> (a,b) { a * b }, converted, RULE_NUMBERS).reduce(:+).divmod 10)[1] == 0
end
gender(id) click to toggle source

Returns gender for given ID. By check the second digit of ID. 1 is male, 2 is female.

# File lib/dixon/validators/taiwan.rb, line 62
def gender(id)
  case id[1]
    when '1' then 'male'
    when '2' then 'female'
    else puts INVALID_MESSAGE
  end
end
issued_by(id) click to toggle source

Returns local agencies who issued your id.

# File lib/dixon/validators/taiwan.rb, line 72
def issued_by(id)
  LETTER_ISSUED_BY[id[0]]
end

Private Instance Methods

convert(id) click to toggle source

Convert an identification number to array of strings First letter conversion rules is defined in LETTER_NUMBERS ‘convert ’F127337575’‘ will result in

1, 5, 1, 2, 7, 3, 3, 7, 5, 7, 5
# File lib/dixon/validators/taiwan.rb, line 89
def convert(id)
  to_i_array((LETTER_NUMBERS[id[0]] + id[1..-1]).split(''))
end
mapcar(fn, *arrs) click to toggle source

mapcar operates on successive elements of the arrays. fn is applied to the first element of each array, then to the secondf element of each array, and so on. The iteration terminates when the shortest array runs out, and excess elements in other arrays are ignored. The value returned by mapcar is a array of the results of successive calls to function.

# File lib/dixon/validators/taiwan.rb, line 101
def mapcar(fn, *arrs)
  return [] if arrs.empty? or arrs.include? []
  transposed = if arrs.element_of_same_size
                 arrs.transpose
               else
                 arrs[0].zip(*arrs.drop(1))
               end
  transposed.map do |e|
    e.reduce(&fn) unless e.include? nil
  end
end
to_i_array(str_arr) click to toggle source

Convert array of strings into integer array.

# File lib/dixon/validators/taiwan.rb, line 80
def to_i_array(str_arr)
  str_arr.map(&:to_i)
end