Module: ApiEntreprise::Commons::Siren

Defined in:
lib/api_entreprise/commons/siren.rb

Constant Summary collapse

DIGITS_9 =
/\A\d{9}\z/.freeze
LA_POSTE_PATTERN =
/\A356000000\z/.freeze

Class Method Summary collapse

Class Method Details

.luhn_checksum(value) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/api_entreprise/commons/siren.rb', line 27

def luhn_checksum(value)
  accum = 0
  value.reverse.each_char.map(&:to_i).each_with_index do |digit, index|
    t = index.even? ? digit : digit * 2
    t -= 9 if t >= 10
    accum += t
  end
  accum
end

.valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
16
17
18
# File 'lib/api_entreprise/commons/siren.rb', line 12

def valid?(value)
  return false if value.nil?
  return false unless value.to_s.match?(DIGITS_9)
  return true if value.to_s.match?(LA_POSTE_PATTERN)

  (luhn_checksum(value.to_s) % 10).zero?
end

.validate!(value, parameter:) ⇒ Object

Raises:



20
21
22
23
24
25
# File 'lib/api_entreprise/commons/siren.rb', line 20

def validate!(value, parameter:)
  return if valid?(value)

  raise InvalidSirenError,
        "#{parameter.inspect} must be a 9-digit SIREN passing the Luhn checksum; got #{value.inspect}"
end