Module: BrazilianUtils::CNAEUtils

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

Overview

Utilities for the CNAE-Subclasses 2.3 table (the current subclass revision of CNAE 2.0), sourced from the IBGE CONCLA API.

Constant Summary collapse

DATA_FILE =
File.join(File.dirname(__FILE__), 'data', 'cnae.json')

Class Method Summary collapse

Class Method Details

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

Formats a CNAE subclass code with the mask NNNN-N/NN; the mask is applied as far as the digits go (only the structure changes — use is_valid to check the code).

Parameters:

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

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

Returns:

  • (String) —

    An empty string when there is no digit at all.



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

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

  apply_mask(digits, [4, 1, 2], ['-', '/'])
end

.get(value) ⇒ Hash?

Looks a CNAE subclass code up and returns its (bare, 7-digit) code and official description.

Parameters:

  • value (String, Integer)

Returns:

  • (Hash, nil)


85
86
87
88
89
90
91
# File 'lib/brazilian-utils/cnae-utils.rb', line 85

def self.get(value)
  code = normalize(value)
  return nil unless code

  description = load_data[code]
  description && { code: code, description: description }
end

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

Checks whether a CNAE subclass code exists in the table.

Parameters:

  • value (String, Integer)

Returns:

  • (Boolean)


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

def self.is_valid(value)
  code = normalize(value)
  return false unless code

  load_data.key?(code)
end

.parse(value) ⇒ String

Removes CNAE formatting and keeps only digits, capped to 7 digits (nothing is left-padded).

Parameters:

  • value (String, Integer)

Returns:

  • (String)


98
99
100
101
102
# File 'lib/brazilian-utils/cnae-utils.rb', line 98

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

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