Skip to content

Commit

Permalink
EANs may strip leading zeros
Browse files Browse the repository at this point in the history
  • Loading branch information
Bahanix committed Jan 13, 2017
1 parent 07e95c9 commit c6e264f
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 5 deletions.
8 changes: 3 additions & 5 deletions lib/ean_validator.rb
Expand Up @@ -13,18 +13,16 @@ def validate_each(record, attribute, value)
def valid?(ean)
return false if ean.blank?
return false unless ean =~ /^\d+$/
return false unless [8, 13].include?(ean.length)
return false unless (8..13).include?(ean.length)
return false unless calc_check_digit(ean)

true
end

def calc_check_digit(ean)
coefficient_table = (ean.length == 8) ? EAN_CHECK_DIGIT8 : EAN_CHECK_DIGIT13
ean.split(//).each_with_index.inject(0){ |s, (v, i)| s + v.to_i * coefficient_table[i] } % 10 == 0
ean.rjust(13, "0".freeze).each_char.map.with_index { |char, i| char.to_i * EAN_CHECK_DIGIT13[i] }.reduce(:+) % 10 == 0
end

EAN_CHECK_DIGIT8 = [3, 1, 3, 1, 3, 1, 3, 1]
EAN_CHECK_DIGIT13 = [1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1]
private_constant :EAN_CHECK_DIGIT8, :EAN_CHECK_DIGIT13
private_constant :EAN_CHECK_DIGIT13
end
1 change: 1 addition & 0 deletions test/lib/ean_validator_test.rb
Expand Up @@ -25,6 +25,7 @@ def test_valid
8001094222110
4690432004682
5901234123457
773602403936
46009333
96385074
01234565
Expand Down

0 comments on commit c6e264f

Please sign in to comment.