Class: ImeiValidator

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

Instance Method Summary collapse

Instance Method Details

#valid(imei) ⇒ Object



4
5
6
7
8
9
10
11
12
# File 'lib/rails_imei_validator.rb', line 4

def valid(imei)
    return false if imei.blank?
    digits = imei.reverse.chars.map(&:to_i)
    digits.each_with_index.inject(0) do |sum, (digit, i)|
      digit *= 2 if i.odd?
      digit -= 9 if digit > 9
      sum += digit
    end % 10 == 0
end

#validate_each(record, attribute, value) ⇒ Object



14
15
16
# File 'lib/rails_imei_validator.rb', line 14

def validate_each(record, attribute, value)
  record.errors.add(attribute, :invalid) unless valid(value)
end