Sha256: 9924315900dfe33f7437bc3d40590a20f62f839223de439ed9f83540f9b3ca09

Contents?: true

Size: 875 Bytes

Versions: 6

Compression:

Stored size: 875 Bytes

Contents

module ActiveModel
  module Validations
    class SirenValidator < EachValidator
      # Validates siren format according to
      # http://fr.wikipedia.org/wiki/SIREN
      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

      def validate_each(record, attribute, value)
        if value.nil?
          record.errors.add_on_blank(attribute)
        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
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
activevalidators-3.3.0 lib/active_validators/active_model/validations/siren_validator.rb
activevalidators-3.2.0 lib/active_validators/active_model/validations/siren_validator.rb
activevalidators-3.1.2 lib/active_model/validations/siren_validator.rb
activevalidators-3.1.1 lib/active_model/validations/siren_validator.rb
activevalidators-3.0.0 lib/active_model/validations/siren_validator.rb
activevalidators-2.1.0 lib/active_model/validations/siren_validator.rb