Module: BrazilianUtils::CEIUtils

Defined in:
lib/brazilian-utils/cei-utils.rb

Overview

Utilities for the CEI (Cadastro Específico do INSS), a 12-digit registration number for a work/construction site or rural employer.

Constant Summary collapse

WEIGHTS =
[7, 4, 1, 8, 5, 2, 1, 6, 3, 7, 4].freeze

Class Method Summary collapse

Class Method Details

.format(value, options = {}) ⇒ String

Formats a CEI with the mask 00.000.00000/00, applied as far as the digits go.

Parameters:

  • value (String, Integer)
  • options (Hash) (defaults to: {}) —

    :pad left-pads with zeros to 12 digits first.

Returns:

  • (String)


61
62
63
64
65
66
67
# File 'lib/brazilian-utils/cei-utils.rb', line 61

def self.format(value, options = {})
  digits = value.to_s.gsub(/\D/, '')
  digits = digits.rjust(12, '0') if options[:pad] || options['pad']
  return '' if digits.empty?

  apply_mask(digits, [2, 3, 5, 2], ['.', '.', '/'])
end

.is_valid(value) ⇒ Boolean Also known as: valid?

Validates a CEI: 12 digits, 11 base digits and one check digit.

Parameters:

  • value (String, Integer) —

    Bare digits, or split into the printed groups (2, 3, 5 and 2 digits) by whitespace or the usual mask characters (., -, /).

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/brazilian-utils/cei-utils.rb', line 38

def self.is_valid(value)
  return false unless value.is_a?(String) || value.is_a?(Integer)

  raw = value.to_s.strip
  return false unless raw.match?(%r{\A[\d\s.\-/]+\z})

  digits = raw.gsub(%r{[\s.\-/]}, '')
  return false unless digits.match?(/\A\d{12}\z/)
  return false if digits.chars.uniq.length == 1

  digits[11].to_i == check_digit(digits[0, 11])
end

.parse(value) ⇒ String

Removes CEI formatting and keeps only digits, capped to 12 digits.

Parameters:

  • value (String, Integer)

Returns:

  • (String)


73
74
75
76
77
# File 'lib/brazilian-utils/cei-utils.rb', line 73

def self.parse(value)
  return '' unless value.is_a?(String) || value.is_a?(Integer)

  value.to_s.gsub(/\D/, '')[0, 12]
end