Module: BrazilianUtils::CNOUtils

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

Overview

Utilities for the CNO (Cadastro Nacional de Obras), which replaced the CEI for construction works and kept its numbering/check-digit rule.

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 CNO with the mask 00.000.00000/00 (the CEI numbering).

Parameters:

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

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

Returns:

  • (String)


58
59
60
61
62
63
64
# File 'lib/brazilian-utils/cno-utils.rb', line 58

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 CNO: same rules as CEIUtils#is_valid.

Parameters:

  • value (String, Integer)

Returns:

  • (Boolean)


36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/brazilian-utils/cno-utils.rb', line 36

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 CNO formatting and keeps only digits, capped to 12 digits.

Parameters:

  • value (String, Integer)

Returns:

  • (String)


70
71
72
73
74
# File 'lib/brazilian-utils/cno-utils.rb', line 70

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

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