class ActiveModel::Validations::SirenValidator

Public Instance Methods

valid_siren?(input) click to toggle source

Validates siren format according to fr.wikipedia.org/wiki/SIREN

# File lib/active_validators/active_model/validations/siren_validator.rb, line 6
def valid_siren?(input)
  str = input.to_s
  reversed_array = str.split('').reverse

  digits = reversed_array.each_with_index.map do |char, i|
    coeff = (i % 2) + 1
    (char.to_i * coeff).to_s.split('')
  end

  sum = digits.flatten.map(&:to_i).inject(:+)

  (sum % 10) == 0
end
validate_each(record, attribute, value) click to toggle source
# File lib/active_validators/active_model/validations/siren_validator.rb, line 20
def validate_each(record, attribute, value)
  if value.nil?
    record.errors.add(attribute, :blank)
  else
    if value.to_s.length != 9
      record.errors.add attribute, :length
    else
      record.errors.add attribute, :format unless valid_siren?(value)
    end
  end
end