Created
August 27, 2013 12:26
-
-
Save paracycle/6352876 to your computer and use it in GitHub Desktop.
Rails TCKN validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TcknValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
unless validate_tckn(value) | |
record.errors.add(attribute, options[:message] || :invalid) | |
end | |
end | |
protected | |
def validate_tckn(tckn) | |
digits = tckn[0..8].each_char.map(&:to_i).each_with_index | |
first, last = | |
digits.reduce([0, 0]) do |memo, (digit, idx)| | |
add = digit * (idx.even? ? 7 : -1) | |
[ | |
# Multiply all even digits with 7 and odd digits with -1 and sum | |
(memo.first + add) % 10, | |
# Sum all the digits and add the first sum. We add the first sum | |
# by accumulating it on to this number as well. | |
(memo.last + digit + add) % 10 | |
] | |
end | |
tckn[9] == first.to_s && tckn[10] == last.to_s | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment