br-utilities for Ruby

Gem Version Gem Downloads Ruby Version Test Status Last Update Date Project License

πŸš€ Full support for the new alphanumeric CNPJ format.

🌎 Acessar documentaΓ§Γ£o em portuguΓͺs

A Ruby toolkit to handle the main operations with Brazilian-related data: CPF (Individual's Taxpayer ID) and CNPJ (Business Tax ID). It wraps cpf-utilities and cnpj-utilities in a single faΓ§ade class (BrUtils).

Ruby Support

Ruby 3.1 Ruby 3.2 Ruby 3.3 Ruby 3.4 Ruby 4.0
Passing βœ” Passing βœ” Passing βœ” Passing βœ” Passing βœ”

Requires Ruby β‰₯ 3.1 (see required_ruby_version in the gemspec).

Features

  • βœ… Unified top-level API: Class helpers BrUtils.cpf / .cnpj delegate to BrUtils::DEFAULT.cpf / .cnpj; each domain offers format, generate, and is_valid
  • βœ… Bundled domains: cpf-utilities and cnpj-utilities installed together
  • βœ… Alphanumeric CNPJ: Full support for the new alphanumeric CNPJ format (introduced in 2026)
  • βœ… Reusable instance: BrUtils class with optional default CPF and CNPJ settings (nested mappings, flat component kwargs, or pre-built utils instances)
  • βœ… Two-tier access: Prefer main-class shortcuts at the faΓ§ade root (BrUtils::CpfFormatter, BrUtils::CnpjValidator, …); Options, helpers, and errors live under nested package modules (BrUtils::CpfFmt, BrUtils::CnpjUtils, …). Root siblings (CpfUtils, CnpjUtils, CpfFmt, …) still work
  • βœ… Per-call overrides: Configure defaults on the faΓ§ade / domain utils; override options on a single format / generate / is_valid call
  • βœ… Error handling: Domain errors propagate unchanged from the bundled packages; this gem defines BrUtils::TypeMismatchError and BrUtils::InvalidArgumentCombinationError for API misuse

Installation

Install the gem directly:

gem install br-utilities

Or add it to your Gemfile and run bundle install:

gem 'br-utilities'

This installs br-utilities together with cpf-utilities and cnpj-utilities (which in turn pull in the CPF and CNPJ component packages). You do not need separate gem install / gem lines for the domain packages when using br-utilities.

Require

require 'br-utilities'

Quick Start

Prefer the aggregator class helpers (BrUtils.cpf / BrUtils.cnpj) for one-off calls β€” they forward to BrUtils::DEFAULT:

require 'br-utilities'

cpf = '12345678909'
cnpj = '03603568000195'

# CPF (personal ID)
BrUtils.cpf.format(cpf)              # => "123.456.789-09"
BrUtils.cpf.generate(format: true)   # => e.g. "478.442.410-55"
BrUtils.cpf.is_valid('123.456.789-09') # => true

# CNPJ (business ID)
BrUtils.cnpj.format(cnpj)            # => "03.603.568/0001-95"
BrUtils.cnpj.generate(format: true)  # => e.g. "AB.123.CDE/0001-55"
BrUtils.cnpj.is_valid('98765432000198') # => true

With domain aggregators:

require 'br-utilities'

cpf = '12345678909'
cnpj = '03603568000195'

CpfUtils.format(cpf)      # => "123.456.789-09"
CnpjUtils.format(cnpj)    # => "03.603.568/0001-95"
CpfUtils.is_valid(cpf)    # => true
CnpjUtils.is_valid(cnpj)  # => true

With functional helpers (root sibling modules, loaded by this gem):

require 'br-utilities'

cpf = '12345678909'
cnpj = '03603568000195'

CpfFmt.cpf_fmt(cpf)     # => "123.456.789-09"
CpfVal.cpf_val(cpf)     # => true
CnpjFmt.cnpj_fmt(cnpj)  # => "03.603.568/0001-95"
CnpjVal.cnpj_val(cnpj)  # => true

Usage

You can work in these equivalent ways:

  1. BrUtils.cpf / .cnpj β€” class helpers for quick one-off calls (forward to DEFAULT).
  2. BrUtils::DEFAULT β€” mutable shared singleton (same object the class helpers use; process-wide / not thread-isolated).
  3. BrUtils.new β€” configurable instance with shared defaults across both CPF and CNPJ domains.
  4. Domain aggregators β€” CpfUtils / CnpjUtils (or BrUtils::CpfUtils / BrUtils::CnpjUtils) directly.
  5. Main classes under BrUtils β€” BrUtils::CpfFormatter, BrUtils::CnpjGenerator, and related shortcuts.
  6. Nested package modules β€” Options, helpers, errors, and types via BrUtils::CpfFmt / CpfGen / CpfVal / CnpjFmt / CnpjGen / CnpjVal / CpfUtils / CnpjUtils.
  7. Root sibling modules (still supported) β€” CpfFmt, CnpjUtils, and the rest unchanged.

All approaches expose the same options and behavior within each domain. For exhaustive option tables and component-specific details, see the README of each bundled package.

Class helpers (BrUtils.cpf / .cnpj)

These class methods return the same domain utils instances as BrUtils::DEFAULT. Prefer them for one-off calls:

BrUtils.cpf.format('12345678909')
BrUtils.cpf.generate(format: true)
BrUtils.cpf.is_valid('12345678909')

BrUtils.cnpj.format('03603568000195')
BrUtils.cnpj.generate(type: 'numeric')
BrUtils.cnpj.is_valid('98765432000198')

BrUtils::DEFAULT (default instance)

BrUtils::DEFAULT is the pre-built, mutable singleton behind the class helpers (parity with the JS default export / Python br_utils). Its configuration is process-wide and shared across threads: mutating it (e.g. DEFAULT.cpf = …) affects subsequent BrUtils.cpf / .cnpj calls for every caller in the process. Prefer BrUtils.new or per-call options for concurrent or isolated work; custom instances stay independent of DEFAULT:

BrUtils::DEFAULT.cpf = CpfUtils.new(formatter: { dash_key: '|' })
BrUtils.cpf.format('12345678909')   # => "123.456.789|09"

custom = BrUtils.new
custom.cpf.format('12345678909')    # => "123.456.789-09" (unaffected)

BrUtils (class)

For custom default CPF or CNPJ utils, create your own instance:

require 'br-utilities'

utils = BrUtils.new(
  cpf: {
    formatter: { hidden: true, hidden_key: '#' },
    generator: { format: true }
  },
  cnpj: {
    formatter: { hidden: true },
    generator: { type: 'numeric', format: true },
    validator: { type: 'numeric' }
  }
)

utils.cpf.format('12345678909')        # => "123.###.###-##"
utils.cpf.generate                     # => e.g. "005.265.352-88"
utils.cnpj.format('03603568000195')    # => "03.603.***/****-**"
utils.cnpj.generate                    # => e.g. "73.008.535/0005-06"

# Access or replace internal domain instances
utils.cpf    # => CpfUtils
utils.cnpj   # => CnpjUtils
  • BrUtils.new(settings = nil, **keywords): Optional settings. Pass either a settings Hash with :cpf and/or :cnpj keys, or the same keys (plus flat component kwargs) as keyword arguments β€” not both (passing both raises BrUtils::InvalidArgumentCombinationError).
    • :cpf / :cnpj: A pre-built CpfUtils / CnpjUtils instance or a configuration Hash spread into the corresponding utils constructor. Within that Hash, each resource key (:formatter, :generator, and :validator for CNPJ) accepts either an options object or a mapping of option values.
    • :cpf_formatter, :cpf_generator, :cnpj_formatter, :cnpj_generator, :cnpj_validator: Flat convenience arguments when only individual components need customization. They are ignored when the corresponding :cpf or :cnpj argument is provided.
  • #cpf, #cnpj: Accessors (getters and setters) for the domain utils instances. Setters accept a utils instance, a configuration Hash, or nil to reset to defaults (replaces the entire instance; does not merge).

Flat constructor options (alternative to nested :cpf / :cnpj mappings):

require 'br-utilities'

utils = BrUtils.new(
  cpf_formatter: CpfFmt::CpfFormatterOptions.new(hidden: true, hidden_key: '#'),
  cpf_generator: CpfGen::CpfGeneratorOptions.new(format: true),
  cnpj_formatter: CnpjFmt::CnpjFormatterOptions.new(hidden: true, hidden_key: '#'),
  cnpj_generator: CnpjGen::CnpjGeneratorOptions.new(format: true, type: 'numeric'),
  cnpj_validator: CnpjVal::CnpjValidatorOptions.new(type: 'numeric')
)

Passing a settings Hash positional argument together with any keyword raises:

BrUtils.new({ cpf: {} }, cnpj: CnpjUtils.new)
# raises BrUtils::InvalidArgumentCombinationError

Instance defaults and per-call overrides

require 'br-utilities'

utils = BrUtils.new(
  cpf: {
    formatter: { hidden: true, hidden_key: '#' },
    generator: { format: true }
  },
  cnpj: {
    formatter: { hidden: true, hidden_key: '#' },
    generator: { format: true },
    validator: { type: 'numeric' }
  }
)

cpf = '12345678909'
cnpj = '03603568000195'

utils.cpf.format(cpf)                  # => "123.###.###-##"
utils.cpf.format(cpf, hidden: false)   # this call only: unmasked
utils.cpf.generate(format: false)      # this call only: compact output

utils.cnpj.format(cnpj)                  # => "03.603.###/####-##"
utils.cnpj.format(cnpj, hidden: false)   # this call only: unmasked
utils.cnpj.is_valid('1QB5UKALPYFP59')    # => false (instance validator is numeric-only)
utils.cnpj.is_valid(                     # => true for this call
  '1QB5UKALPYFP59',
  type: 'alphanumeric'
)

Passing a CnpjFmt::CnpjFormatterOptions, CnpjGen::CnpjGeneratorOptions, or CnpjVal::CnpjValidatorOptions instance into the BrUtils constructor stores that object by reference β€” mutating it later affects subsequent calls with no per-call override.

To change a single nested option without replacing the whole domain utils, mutate via the domain accessors (e.g. utils.cpf.formatter.options.hidden = true).

CPF operations

CPF methods are accessed via BrUtils.cpf, utils.cpf, CpfUtils, or the CpfFmt / CpfGen / CpfVal helpers. CPF uses the API from cpf-utilities.

Formatting (#format / CpfFmt.cpf_fmt)

Option Type Default Description
hidden Boolean false When true, mask digits in hidden_start–hidden_end with hidden_key
hidden_key String '*' Character(s) used to replace masked digits
hidden_start Integer 3 Start index (0–10, inclusive) of the range to hide
hidden_end Integer 10 End index (0–10, inclusive) of the range to hide
dot_key String '.' Dot delimiter (e.g. in 123.456.789)
dash_key String '-' Dash delimiter (e.g. before check digits …-09)
escape Boolean false When true, escape HTML special characters in the result
encode Boolean false When true, URL-encode the result (similar to JavaScript encodeURIComponent)
on_fail Proc / callable returns '' Callback when sanitized input length β‰  11; return value is used as result

Default on_fail returns an empty string. Invalid length does not raise from #format.

require 'br-utilities'

cpf = '12345678909'

BrUtils.cpf.format(cpf)                              # => "123.456.789-09"
BrUtils.cpf.format(cpf, hidden: true, hidden_key: '#') # => "123.###.###-##"
BrUtils.cpf.format(cpf, dot_key: '', dash_key: '_')  # => "123456789_09"

CpfFmt.cpf_fmt(cpf, hidden: true)                    # => "123.***.***-**"

Generation (#generate / CpfGen.cpf_gen)

Option Type Default Description
format Boolean false When true, return the generated CPF in standard format (000.000.000-00)
prefix String '' Partial start string (0–9 digits). Non-digits are stripped; missing characters are generated and check digits computed. Prefixes longer than 9 digits are truncated silently.

Prefix rules: the base (first 9 digits) cannot be all zeros; 9 repeated digits (e.g. 999999999) are not allowed.

require 'br-utilities'

BrUtils.cpf.generate                       # => e.g. "11508890048"
BrUtils.cpf.generate(format: true)         # => e.g. "661.134.831-00"
BrUtils.cpf.generate(prefix: '123456789')  # => "12345678909"
CpfGen.cpf_gen(prefix: '123456789', format: true) # => "123.456.789-09"

Validation (#is_valid / CpfVal.cpf_val)

Accepts formatted or unformatted CPF strings (or an Array of strings). Returns true or false without raising for invalid CPF. No validator options exist.

require 'br-utilities'

BrUtils.cpf.is_valid('12345678909')      # => true
BrUtils.cpf.is_valid('123.456.789-09')   # => true
BrUtils.cpf.is_valid('12345678900')      # => false
CpfVal.cpf_val('12345678909')            # => true

CNPJ operations

CNPJ methods are accessed via BrUtils.cnpj, utils.cnpj, CnpjUtils, or the CnpjFmt / CnpjGen / CnpjVal helpers. CNPJ uses the API from cnpj-utilities.

Formatting (#format / CnpjFmt.cnpj_fmt)

Option Type Default Description
hidden Boolean false When true, mask characters in hidden_start–hidden_end with hidden_key
hidden_key String '*' Character(s) used to replace masked characters
hidden_start Integer 5 Start index (0–13, inclusive) of the range to hide
hidden_end Integer 13 End index (0–13, inclusive) of the range to hide
dot_key String '.' Dot delimiter (e.g. in 12.345.678)
slash_key String '/' Slash delimiter (e.g. before branch …/0001-90)
dash_key String '-' Dash delimiter (e.g. before check digits …-90)
escape Boolean false When true, escape HTML special characters in the result
encode Boolean false When true, URL-encode the result (similar to JavaScript encodeURIComponent)
on_fail Proc / callable returns '' Callback when sanitized input length β‰  14; return value is used as result

Default on_fail returns an empty string. Wrong input types raise CnpjFmt::TypeMismatchError.

require 'br-utilities'

cnpj = '03603568000195'

BrUtils.cnpj.format(cnpj)              # => "03.603.568/0001-95"
BrUtils.cnpj.format('12ABC34500DE99')  # => "12.ABC.345/00DE-99"
BrUtils.cnpj.format(                   # => "03.603.###/####-##"
  cnpj,
  hidden: true,
  hidden_key: '#'
)
BrUtils.cnpj.format(                   # => "03603568|0001_95"
  cnpj,
  dot_key: '',
  slash_key: '|',
  dash_key: '_'
)

CnpjFmt.cnpj_fmt(cnpj)                 # => "03.603.568/0001-95"

Generation (#generate / CnpjGen.cnpj_gen)

Option Type Default Description
format Boolean false When true, return the generated CNPJ in standard format (00.000.000/0000-00)
prefix String '' Partial start string (0–12 alphanumeric chars). Missing characters are generated and check digits computed.
type String 'alphanumeric' Character set for the randomly generated part: 'numeric', 'alphabetic', or 'alphanumeric'. Check digits are always numeric.

Prefix rules: base ID (first 8 chars) and branch ID (chars 9–12) cannot be all zeros; 12 repeated digits (e.g. 111111111111) are also not allowed.

require 'br-utilities'

BrUtils.cnpj.generate               # => e.g. "1GJTR3J3XSSA96"
BrUtils.cnpj.generate(format: true) # => e.g. "V1.J0V.8WE/DVZ7-50"
BrUtils.cnpj.generate(              # => e.g. "12345678855883"
  prefix: '12345678',
  type: 'numeric'
)
CnpjGen.cnpj_gen(type: 'numeric')   # => e.g. "65453043000178"

Validation (#is_valid / CnpjVal.cnpj_val)

Option Type Default Description
case_sensitive Boolean true When false, lowercase letters are accepted for alphanumeric CNPJ (input is uppercased before validation).
type String 'alphanumeric' 'numeric': only digits (0–9); 'alphanumeric': digits and letters (0–9, A–Z).
require 'br-utilities'

BrUtils.cnpj.is_valid('98765432000198')   # => true
BrUtils.cnpj.is_valid('98765432000199')   # => false
BrUtils.cnpj.is_valid('1QB5UKALPYFP59')   # => true
BrUtils.cnpj.is_valid('1QB5UKALpyfp59')   # => false
BrUtils.cnpj.is_valid(                     # => true
  '1QB5UKALpyfp59',
  case_sensitive: false
)
BrUtils.cnpj.is_valid(                     # => false
  '1QB5UKALPYFP59',
  type: 'numeric'
)

CnpjVal.cnpj_val('98765432000198')                         # => true
CnpjVal.cnpj_val('1QB5UKALpyfp59', case_sensitive: false)  # => true
CnpjVal.cnpj_val('1QB5UKALPYFP59', type: 'numeric')        # => false

Invalid CNPJ returns false without raising. Wrong input types raise CnpjVal::TypeMismatchError.

Domain aggregators (standalone)

Use CpfUtils or CnpjUtils directly when you only need one domain:

require 'br-utilities'

cpf_utils = CpfUtils.new(
  formatter: { hidden: true },
  generator: { format: true }
)

cnpj_utils = CnpjUtils.new(
  formatter: { hidden: true },
  generator: { format: true },
  validator: { type: 'numeric' }
)

cpf_utils.format('12345678909')       # => "123.***.***-**"
cnpj_utils.format('03603568000195')   # => "03.603.***/****-**"

Accessing components

Each domain aggregator exposes its internal formatter, generator, and validator:

require 'br-utilities'

utils = BrUtils.new

utils.cpf.formatter.format('12345678909', hidden: true)  # => "123.***.***-**"
utils.cpf.generator.generate(format: true)               # => e.g. "545.507.690-68"
utils.cpf.validator.is_valid('12345678909')              # => true

utils.cnpj.formatter.format('12ABC34500DE99')            # => "12.ABC.345/00DE-99"
utils.cnpj.generator.generate(format: true)              # => e.g. "8O.BE5.2KL/UI0Y-06"
utils.cnpj.validator.is_valid('03603568000195')          # => true

Using component classes and nested modules

Preferred paths after require 'br-utilities':

require 'br-utilities'

# Main classes at the faΓ§ade root
formatter = BrUtils::CpfFormatter.new(hidden: true)
generator = BrUtils::CnpjGenerator.new(type: 'numeric')
validator = BrUtils::CnpjValidator.new

formatter.format('12345678909')   # => "123.***.***-**"

# Options, helpers, and errors under nested package modules
options = BrUtils::CpfFmt::CpfFormatterOptions.new(dash_key: '|')
BrUtils::CpfFmt.cpf_fmt('12345678909')   # => "123.456.789-09"

begin
  BrUtils::CnpjFmt.cnpj_fmt(12_345)
rescue BrUtils::CnpjFmt::TypeMismatchError
  # wrong input type
end

Root siblings remain supported (same objects as the nests):

CpfFmt.cpf_fmt('12345678909', dash_key: '|')   # => "123.456.789|09"
CpfGen.cpf_gen(format: true)                   # => e.g. "478.442.410-55"
CpfVal.cpf_val('12345678909')                  # => true
CnpjFmt.cnpj_fmt('01ABC234000X56', slash_key: '|') # => "01.ABC.234|000X-56"
CnpjGen.cnpj_gen(type: 'numeric')              # => e.g. "65453043000178"
CnpjVal.cnpj_val('9JN7MGLJZXIO50')             # => true

See cpf-utilities and cnpj-utilities for full option and error details.

Mixing styles

Use BrUtils where a shared configuration helps, and standalone components or helpers elsewhere β€” they are the same underlying classes:

require 'br-utilities'

utils = BrUtils.new(cnpj: { validator: { type: 'numeric' } })

# Via faΓ§ade
utils.cpf.format('12345678909')   # => "123.456.789-09"

# Via component returned by the faΓ§ade
utils.cnpj.formatter.format('12ABC34500DE99')   # => "12.ABC.345/00DE-99"

# Via a separate component instance
BrUtils::CnpjFormatter.new.format('03603568000195')   # => "03.603.568/0001-95"

# Via functional helpers
CpfFmt.cpf_fmt('12345678909')           # => "123.456.789-09"
CnpjVal.cnpj_val('98.765.432/0001-98')  # => true

API

Exports

After require 'br-utilities':

  • BrUtils: FaΓ§ade class to create an instance with optional default CPF and CNPJ utils settings.
  • BrUtils.cpf / .cnpj: Class helpers that forward to BrUtils::DEFAULT domain accessors.
  • BrUtils::DEFAULT: Mutable pre-built BrUtils instance (same object the class helpers use). Process-wide / shared across threads β€” prefer BrUtils.new or per-call options under concurrency.
  • BrUtils::VERSION: Gem version string.
  • Main-class shortcuts: BrUtils::CpfFormatter, BrUtils::CpfFormatterOptions, BrUtils::CpfGenerator, BrUtils::CpfGeneratorOptions, BrUtils::CpfValidator, BrUtils::CnpjFormatter, BrUtils::CnpjFormatterOptions, BrUtils::CnpjGenerator, BrUtils::CnpjGeneratorOptions, BrUtils::CnpjValidator, BrUtils::CnpjValidatorOptions (same objects as the sibling classes). Error-marker shortcuts: BrUtils::CpfFormatterError, BrUtils::CpfGeneratorError, BrUtils::CpfValidatorError, BrUtils::CnpjFormatterError, BrUtils::CnpjGeneratorError, BrUtils::CnpjValidatorError.
  • Nested package modules: BrUtils::CpfUtils, BrUtils::CnpjUtils, BrUtils::CpfFmt, BrUtils::CpfGen, BrUtils::CpfVal, BrUtils::CnpjFmt, BrUtils::CnpjGen, BrUtils::CnpjVal β€” full sibling surface (Options, helpers, errors, types).
  • Root sibling modules (still supported): CpfUtils, CnpjUtils, CpfFmt, CpfGen, CpfVal, CnpjFmt, CnpjGen, CnpjVal β€” same objects as the nests.

Errors & Exceptions

BrUtils defines only API-misuse errors for this gem’s argument rules. Domain errors are raised by the bundled packages and propagate unchanged.

Defined by br-utilities

Errors defined by this gem are API misuse only (wrong type or invalid argument combination). Every custom error includes the BrUtils::Error marker module. This gem defines no BrUtils::DomainError and no domain leaves β€” domain failures come only from the bundled packages and keep those packages’ namespaces (CpfFmt::…, CnpjGen::…, …).

rescue BrUtils::Error catches only errors this gem raises. It does not catch component errors that propagate unchanged.

Summary
Class Inherits from Category Trigger condition
BrUtils::InvalidArgumentCombinationError BrUtils::InvalidArgumentCombinationError < ArgumentError < StandardError (+ include BrUtils::Error) API misuse Non-nil settings Hash passed together with any non-nil keyword argument
BrUtils::TypeMismatchError BrUtils::TypeMismatchError < TypeError < StandardError (+ include BrUtils::Error) API misuse Non-nil settings argument to BrUtils.new is not a Hash
BrUtils::Error (marker module)
  • Inheritance: module marker mixed into every custom error this gem raises via include (not a class).
  • Category: N/A (rescue target only) β€” not a failure mode by itself.
  • When it is raised: Never raised directly; included by every custom error this gem raises.
  • Example: N/A
  • How to rescue it:
rescue BrUtils::Error
  # TypeMismatchError, InvalidArgumentCombinationError from this gem only
  # (not CpfFmt::*, CnpjGen::*, or other bundled-package errors)
BrUtils::TypeMismatchError
  • Inheritance: BrUtils::TypeMismatchError < TypeError < StandardError (includes BrUtils::Error)
  • Category: API misuse β€” the caller passed a value of the wrong type.
  • When it is raised: Raised when BrUtils.new receives a non-nil settings argument that is not a Hash.
  • Example:
BrUtils.new('not-a-hash')   # raises BrUtils::TypeMismatchError
BrUtils.new(false)          # raises BrUtils::TypeMismatchError (false is non-nil)
  • How to rescue it:
rescue BrUtils::TypeMismatchError
  # this gem's type-contract violation

rescue TypeError
  # native type errors, including this gem's TypeMismatchError
BrUtils::InvalidArgumentCombinationError
  • Inheritance: BrUtils::InvalidArgumentCombinationError < ArgumentError < StandardError (includes BrUtils::Error)
  • Category: API misuse β€” the caller mixed mutually exclusive argument patterns.
  • When it is raised: Raised when BrUtils.new receives both a non-nil settings Hash and any non-nil keyword argument (cpf:, cnpj:, cpf_formatter:, …) at the same time.
  • Example:
BrUtils.new({ cpf: { formatter: { hidden: true } } }, cnpj: { formatter: { hidden: true } })
# raises BrUtils::InvalidArgumentCombinationError
  • How to rescue it:
rescue BrUtils::InvalidArgumentCombinationError
  # this gem's invalid signature combination

rescue ArgumentError
  # native argument errors, including this gem's InvalidArgumentCombinationError
Rescue granularity

Each level is shown as its own standalone example (do not merge them into one rescue ladder β€” a broad native handler would make narrower clauses unreachable).

require 'br-utilities'

# 1) Single native class β€” catches misuse errors of that kind,
#    including non-library ones already handled elsewhere in the consumer's code.
begin
  BrUtils.new('not-a-hash')
rescue TypeError
  # BrUtils::TypeMismatchError and any other TypeError (library or not)
end

begin
  BrUtils.new({ cpf: {} }, cnpj: CnpjUtils.new)
rescue ArgumentError
  # BrUtils::InvalidArgumentCombinationError and any other ArgumentError (library or not)
end
require 'br-utilities'

# 2) Bundled DomainError β€” this gem defines no DomainError; domain failures
#    come from bundled packages and keep those namespaces (e.g. CpfFmt, CnpjFmt).
begin
  BrUtils.new.cpf.format('12345678909', hidden_start: -1)
rescue CpfFmt::DomainError
  # CpfFmt::OutOfRangeError, CpfFmt::ValidationError, and other DomainError subclasses
end

begin
  BrUtils.new.cnpj.format('91415732000793', hidden_start: -1)
rescue CnpjFmt::DomainError
  # CnpjFmt::OutOfRangeError, CnpjFmt::ValidationError, and other DomainError subclasses
end
require 'br-utilities'

# 3) BrUtils::Error β€” catches everything this gem raises, regardless of native ancestry.
#    Does not catch CpfFmt::*, CnpjGen::*, or other bundled-package errors.
begin
  BrUtils.new('not-a-hash')
rescue BrUtils::Error
  # every custom error that includes BrUtils::Error
end
require 'br-utilities'

# 4) Specific leaf class β€” catches only that exact failure mode.
begin
  BrUtils.new('not-a-hash')
rescue BrUtils::TypeMismatchError
  # only BrUtils::TypeMismatchError
end

Propagated from bundled packages

Component errors keep their package namespaces and propagate unchanged through the faΓ§ade (and via nested / root sibling APIs). Each package also exposes an *::Error marker module for library-wide rescue. Invalid CPF/CNPJ data on #is_valid returns false (no domain raise). Formatting length failure is not raised by #format β€” it is delivered to on_fail as CpfFmt::InvalidLengthError or CnpjFmt::InvalidLengthError (default on_fail returns '').

CpfUtils::* / CnpjUtils::* misuse errors also propagate when nested aggregators are constructed or called through BrUtils. For exhaustive option tables and extra edge cases, see cpf-utilities and cnpj-utilities.

Summary
Class Inherits from Category Trigger condition
CnpjFmt::InvalidArgumentCombinationError CnpjFmt::InvalidArgumentCombinationError < ArgumentError < StandardError (+ include CnpjFmt::Error) API misuse Both an options instance/Hash and any non-nil keyword on CnpjFormatter / cnpj_fmt
CnpjFmt::TypeMismatchError CnpjFmt::TypeMismatchError < TypeError < StandardError (+ include CnpjFmt::Error) API misuse CNPJ input or formatter option has the wrong type (or on_fail return is not a String)
CnpjGen::InvalidArgumentCombinationError CnpjGen::InvalidArgumentCombinationError < ArgumentError < StandardError (+ include CnpjGen::Error) API misuse Both an options instance/Hash and any non-nil keyword on CnpjGenerator / cnpj_gen
CnpjGen::TypeMismatchError CnpjGen::TypeMismatchError < TypeError < StandardError (+ include CnpjGen::Error) API misuse Generator option (format / prefix / type) has the wrong type
CnpjUtils::InvalidArgumentCombinationError CnpjUtils::InvalidArgumentCombinationError < ArgumentError < StandardError (+ include CnpjUtils::Error) API misuse Constructor/#format/#generate/#is_valid/class helpers: non-nil settings/options Hash (or options instance) with any non-nil keyword
CnpjUtils::TypeMismatchError CnpjUtils::TypeMismatchError < TypeError < StandardError (+ include CnpjUtils::Error) API misuse Non-nil settings argument to CnpjUtils.new is not a Hash
CnpjVal::InvalidArgumentCombinationError CnpjVal::InvalidArgumentCombinationError < ArgumentError < StandardError (+ include CnpjVal::Error) API misuse Both an options instance/Hash and any non-nil keyword on CnpjValidator / cnpj_val
CnpjVal::TypeMismatchError CnpjVal::TypeMismatchError < TypeError < StandardError (+ include CnpjVal::Error) API misuse CNPJ input or validator option has the wrong type
CpfFmt::InvalidArgumentCombinationError CpfFmt::InvalidArgumentCombinationError < ArgumentError < StandardError (+ include CpfFmt::Error) API misuse Both an options instance/Hash and any non-nil keyword on CpfFormatter / cpf_fmt
CpfFmt::TypeMismatchError CpfFmt::TypeMismatchError < TypeError < StandardError (+ include CpfFmt::Error) API misuse CPF input or formatter option has the wrong type (or on_fail return is not a String)
CpfGen::InvalidArgumentCombinationError CpfGen::InvalidArgumentCombinationError < ArgumentError < StandardError (+ include CpfGen::Error) API misuse Both an options instance/Hash and any non-nil keyword on CpfGenerator / cpf_gen
CpfGen::TypeMismatchError CpfGen::TypeMismatchError < TypeError < StandardError (+ include CpfGen::Error) API misuse Generator option (format / prefix) has the wrong type
CpfUtils::InvalidArgumentCombinationError CpfUtils::InvalidArgumentCombinationError < ArgumentError < StandardError (+ include CpfUtils::Error) API misuse Constructor: non-nil settings Hash with any non-nil keyword; or #format/#generate/class helpers: non-nil options Hash/*Options with any non-nil keyword
CpfUtils::TypeMismatchError CpfUtils::TypeMismatchError < TypeError < StandardError (+ include CpfUtils::Error) API misuse Non-nil settings argument to CpfUtils.new is not a Hash
CpfVal::TypeMismatchError CpfVal::TypeMismatchError < TypeError < StandardError (+ include CpfVal::Error) API misuse CPF input is not a String or Array of strings
CnpjFmt::InvalidLengthError CnpjFmt::InvalidLengthError < CnpjFmt::DomainError < RangeError < StandardError (+ include CnpjFmt::Error) Domain error Sanitized length β‰  14 β€” passed to on_fail, not raised by #format
CnpjFmt::OutOfRangeError CnpjFmt::OutOfRangeError < CnpjFmt::DomainError < RangeError < StandardError (+ include CnpjFmt::Error) Domain error hidden_start / hidden_end outside 0–13
CnpjFmt::ValidationError CnpjFmt::ValidationError < CnpjFmt::DomainError < RangeError < StandardError (+ include CnpjFmt::Error) Domain error hidden_key / dot_key / slash_key / dash_key contains a disallowed character
CnpjGen::ValidationError CnpjGen::ValidationError < CnpjGen::DomainError < RangeError < StandardError (+ include CnpjGen::Error) Domain error Ineligible prefix, or type not in 'alphabetic' / 'alphanumeric' / 'numeric'
CnpjVal::ValidationError CnpjVal::ValidationError < CnpjVal::DomainError < RangeError < StandardError (+ include CnpjVal::Error) Domain error Validator type is not 'alphanumeric' or 'numeric'
CpfFmt::InvalidLengthError CpfFmt::InvalidLengthError < CpfFmt::DomainError < RangeError < StandardError (+ include CpfFmt::Error) Domain error Sanitized length β‰  11 β€” passed to on_fail, not raised by #format
CpfFmt::OutOfRangeError CpfFmt::OutOfRangeError < CpfFmt::DomainError < RangeError < StandardError (+ include CpfFmt::Error) Domain error hidden_start / hidden_end outside 0–10
CpfFmt::ValidationError CpfFmt::ValidationError < CpfFmt::DomainError < RangeError < StandardError (+ include CpfFmt::Error) Domain error hidden_key / dot_key / dash_key contains a disallowed character
CpfGen::ValidationError CpfGen::ValidationError < CpfGen::DomainError < RangeError < StandardError (+ include CpfGen::Error) Domain error prefix is ineligible (zeroed base or 9 repeated digits)
CpfFmt::DomainError
  • Inheritance: CpfFmt::DomainError < RangeError < StandardError (includes CpfFmt::Error)
  • Category: Domain error β€” ancestor for formatter domain leaves.
  • When it is raised: Not raised directly; rescue target for OutOfRangeError, ValidationError, and re-raised InvalidLengthError.
  • Example: Prefer rescuing a leaf, or CpfFmt::DomainError for all CPF formatter domain failures.
  • How to rescue it:
rescue CpfFmt::DomainError
  # OutOfRangeError, ValidationError, InvalidLengthError (if re-raised from on_fail)
CpfFmt::TypeMismatchError
  • Inheritance: CpfFmt::TypeMismatchError < TypeError < StandardError (includes CpfFmt::Error)
  • Category: API misuse β€” wrong type for CPF input or a formatter option.
  • When it is raised: Raised when #format / cpf_fmt receives a non-String / non-Array<String> input, an option has the wrong type, or on_fail does not return a String.
  • Example:
BrUtils.new.cpf.format(12_345)   # raises CpfFmt::TypeMismatchError
  • How to rescue it:
rescue CpfFmt::TypeMismatchError
  # formatter type-contract violation

rescue TypeError
  # native type errors, including CpfFmt::TypeMismatchError
CpfFmt::InvalidArgumentCombinationError
  • Inheritance: CpfFmt::InvalidArgumentCombinationError < ArgumentError < StandardError (includes CpfFmt::Error)
  • Category: API misuse β€” mixed options and keywords on the formatter API.
  • When it is raised: Raised by CpfFmt::CpfFormatter / CpfFmt.cpf_fmt when both an options instance/Hash and any non-nil keyword are passed. (The CPF aggregator raises CpfUtils::InvalidArgumentCombinationError for the same pattern on CpfUtils#format.)
  • Example:
CpfFmt::CpfFormatter.new({ dash_key: '_' }, hidden: true)
# raises CpfFmt::InvalidArgumentCombinationError
  • How to rescue it:
rescue CpfFmt::InvalidArgumentCombinationError
  # formatter invalid signature combination

rescue ArgumentError
  # native argument errors, including this one
CpfFmt::InvalidLengthError (callback-delivered)
  • Inheritance: CpfFmt::InvalidLengthError < CpfFmt::DomainError < RangeError < StandardError (includes CpfFmt::Error)
  • Category: Domain error β€” sanitized CPF length is not exactly 11.
  • When it is raised: Not raised by #format / cpf_fmt; constructed and passed as the second argument to on_fail.
  • Example:
custom_fail = ->(value, error) {
  error   # => #<CpfFmt::InvalidLengthError ...>
  "Invalid CPF: #{value}"
}

BrUtils.new.cpf.format('123', on_fail: custom_fail)   # => "Invalid CPF: 123"
BrUtils.new.cpf.format('123')                         # => "" (default on_fail)
  • How to rescue it: Handle inside on_fail (typical), or rescue if you re-raise:
rescue CpfFmt::InvalidLengthError
  # this exact length violation

rescue CpfFmt::DomainError
  # RangeError-rooted domain failures from cpf-fmt
CpfFmt::OutOfRangeError
  • Inheritance: CpfFmt::OutOfRangeError < CpfFmt::DomainError < RangeError < StandardError (includes CpfFmt::Error)
  • Category: Domain error β€” hidden_start / hidden_end outside 0–10.
  • When it is raised: Raised when building or applying formatter options with an out-of-range hide index.
  • Example:
BrUtils.new.cpf.format('12345678909', hidden_start: -1)   # raises CpfFmt::OutOfRangeError
  • How to rescue it:
rescue CpfFmt::OutOfRangeError
  # this exact range violation

rescue CpfFmt::DomainError
  # RangeError-rooted domain failures from cpf-fmt
CpfFmt::ValidationError
  • Inheritance: CpfFmt::ValidationError < CpfFmt::DomainError < RangeError < StandardError (includes CpfFmt::Error)
  • Category: Domain error β€” a key option contains a disallowed character.
  • When it is raised: Raised when hidden_key, dot_key, or dash_key contains a forbidden character.
  • Example:
BrUtils.new(cpf: { formatter: { dot_key: 'Γ₯' } })   # raises CpfFmt::ValidationError
  • How to rescue it:
rescue CpfFmt::ValidationError
  # this exact domain validation failure

rescue CpfFmt::DomainError
  # RangeError-rooted domain failures from cpf-fmt
CpfGen::DomainError
  • Inheritance: CpfGen::DomainError < RangeError < StandardError (includes CpfGen::Error)
  • Category: Domain error β€” ancestor for generator domain leaves.
  • When it is raised: Not raised directly; rescue target for CpfGen::ValidationError.
  • Example: Prefer rescue CpfGen::ValidationError or CpfGen::DomainError.
  • How to rescue it:
rescue CpfGen::DomainError
  # ValidationError and other DomainError subclasses from cpf-gen
CpfGen::TypeMismatchError
  • Inheritance: CpfGen::TypeMismatchError < TypeError < StandardError (includes CpfGen::Error)
  • Category: API misuse β€” wrong type for a generator option.
  • When it is raised: Raised when format or prefix has the wrong runtime type.
  • Example:
BrUtils.new.cpf.generate(prefix: 123)   # raises CpfGen::TypeMismatchError
  • How to rescue it:
rescue CpfGen::TypeMismatchError
  # generator type-contract violation

rescue TypeError
  # native type errors, including CpfGen::TypeMismatchError
CpfGen::InvalidArgumentCombinationError
  • Inheritance: CpfGen::InvalidArgumentCombinationError < ArgumentError < StandardError (includes CpfGen::Error)
  • Category: API misuse β€” mixed options and keywords on the generator API.
  • When it is raised: Raised by CpfGen::CpfGenerator / CpfGen.cpf_gen when both an options instance/Hash and any non-nil keyword are passed. (The CPF aggregator raises CpfUtils::InvalidArgumentCombinationError for the same pattern on CpfUtils#generate.)
  • Example:
CpfGen::CpfGenerator.new({ format: true }, prefix: '123')
# raises CpfGen::InvalidArgumentCombinationError
  • How to rescue it:
rescue CpfGen::InvalidArgumentCombinationError
  # generator invalid signature combination

rescue ArgumentError
  # native argument errors, including this one
CpfGen::ValidationError
  • Inheritance: CpfGen::ValidationError < CpfGen::DomainError < RangeError < StandardError (includes CpfGen::Error)
  • Category: Domain error β€” ineligible prefix.
  • When it is raised: Raised when prefix is a zeroed base ('000000000') or 9 repeated digits (e.g. '999999999').
  • Example:
BrUtils.new.cpf.generate(prefix: '000000000')   # raises CpfGen::ValidationError
  • How to rescue it:
rescue CpfGen::ValidationError
  # this exact domain validation failure

rescue CpfGen::DomainError
  # RangeError-rooted domain failures from cpf-gen
CpfVal::TypeMismatchError
  • Inheritance: CpfVal::TypeMismatchError < TypeError < StandardError (includes CpfVal::Error)
  • Category: API misuse β€” wrong type for CPF input.
  • When it is raised: Raised when #is_valid / cpf_val receives a value that is not a String or an Array of strings (including a non-string array element). Invalid CPF data returns false and does not raise.
  • Example:
BrUtils.new.cpf.is_valid(12_345_678_909)   # raises CpfVal::TypeMismatchError
BrUtils.new.cpf.is_valid('12345678900')    # => false (invalid data, no raise)
  • How to rescue it:
rescue CpfVal::TypeMismatchError
  # validator type-contract violation

rescue TypeError
  # native type errors, including CpfVal::TypeMismatchError
CnpjFmt::DomainError
  • Inheritance: CnpjFmt::DomainError < RangeError < StandardError (includes CnpjFmt::Error)
  • Category: Domain error β€” ancestor for formatter domain leaves.
  • When it is raised: Not raised directly; rescue target for OutOfRangeError, ValidationError, and re-raised InvalidLengthError.
  • Example: Prefer rescuing a leaf, or CnpjFmt::DomainError for all CNPJ formatter domain failures.
  • How to rescue it:
rescue CnpjFmt::DomainError
  # OutOfRangeError, ValidationError, InvalidLengthError (if re-raised from on_fail)
CnpjFmt::TypeMismatchError
  • Inheritance: CnpjFmt::TypeMismatchError < TypeError < StandardError (includes CnpjFmt::Error)
  • Category: API misuse β€” wrong type for CNPJ input or a formatter option.
  • When it is raised: Raised when #format / cnpj_fmt receives a non-String / non-Array<String> input, an option has the wrong type, or on_fail does not return a String.
  • Example:
BrUtils.new.cnpj.format(12_345)   # raises CnpjFmt::TypeMismatchError
  • How to rescue it:
rescue CnpjFmt::TypeMismatchError
  # formatter type-contract violation

rescue TypeError
  # native type errors, including CnpjFmt::TypeMismatchError
CnpjFmt::InvalidArgumentCombinationError
  • Inheritance: CnpjFmt::InvalidArgumentCombinationError < ArgumentError < StandardError (includes CnpjFmt::Error)
  • Category: API misuse β€” mixed options and keywords on the formatter API.
  • When it is raised: Raised by CnpjFmt::CnpjFormatter / CnpjFmt.cnpj_fmt when both an options instance/Hash and any non-nil keyword are passed. (The CNPJ aggregator raises CnpjUtils::InvalidArgumentCombinationError for the same pattern on CnpjUtils#format.)
  • Example:
CnpjFmt::CnpjFormatter.new({ slash_key: '|' }, hidden: true)
# raises CnpjFmt::InvalidArgumentCombinationError
  • How to rescue it:
rescue CnpjFmt::InvalidArgumentCombinationError
  # formatter invalid signature combination

rescue ArgumentError
  # native argument errors, including this one
CnpjFmt::InvalidLengthError (callback-delivered)
  • Inheritance: CnpjFmt::InvalidLengthError < CnpjFmt::DomainError < RangeError < StandardError (includes CnpjFmt::Error)
  • Category: Domain error β€” sanitized CNPJ length is not exactly 14.
  • When it is raised: Not raised by #format / cnpj_fmt; constructed and passed as the second argument to on_fail.
  • Example:
custom_fail = ->(value, error) {
  error   # => #<CnpjFmt::InvalidLengthError ...>
  "Invalid CNPJ: #{value}"
}

BrUtils.new.cnpj.format('123', on_fail: custom_fail)   # => "Invalid CNPJ: 123"
BrUtils.new.cnpj.format('123')                         # => "" (default on_fail)
  • How to rescue it: Handle inside on_fail (typical), or rescue if you re-raise:
rescue CnpjFmt::InvalidLengthError
  # this exact length violation

rescue CnpjFmt::DomainError
  # RangeError-rooted domain failures from cnpj-fmt
CnpjFmt::OutOfRangeError
  • Inheritance: CnpjFmt::OutOfRangeError < CnpjFmt::DomainError < RangeError < StandardError (includes CnpjFmt::Error)
  • Category: Domain error β€” hidden_start / hidden_end outside 0–13.
  • When it is raised: Raised when building or applying formatter options with an out-of-range hide index.
  • Example:
BrUtils.new.cnpj.format('91415732000793', hidden_start: -1)   # raises CnpjFmt::OutOfRangeError
  • How to rescue it:
rescue CnpjFmt::OutOfRangeError
  # this exact range violation

rescue CnpjFmt::DomainError
  # RangeError-rooted domain failures from cnpj-fmt
CnpjFmt::ValidationError
  • Inheritance: CnpjFmt::ValidationError < CnpjFmt::DomainError < RangeError < StandardError (includes CnpjFmt::Error)
  • Category: Domain error β€” a key option contains a disallowed character.
  • When it is raised: Raised when hidden_key, dot_key, slash_key, or dash_key contains a forbidden character.
  • Example:
BrUtils.new(cnpj: { formatter: { slash_key: 'Γ₯' } })   # raises CnpjFmt::ValidationError
  • How to rescue it:
rescue CnpjFmt::ValidationError
  # this exact domain validation failure

rescue CnpjFmt::DomainError
  # RangeError-rooted domain failures from cnpj-fmt
CnpjGen::DomainError
  • Inheritance: CnpjGen::DomainError < RangeError < StandardError (includes CnpjGen::Error)
  • Category: Domain error β€” ancestor for generator domain leaves.
  • When it is raised: Not raised directly; rescue target for CnpjGen::ValidationError.
  • Example: Prefer rescue CnpjGen::ValidationError or CnpjGen::DomainError.
  • How to rescue it:
rescue CnpjGen::DomainError
  # ValidationError and other DomainError subclasses from cnpj-gen
CnpjGen::TypeMismatchError
  • Inheritance: CnpjGen::TypeMismatchError < TypeError < StandardError (includes CnpjGen::Error)
  • Category: API misuse β€” wrong type for a generator option.
  • When it is raised: Raised when format, prefix, or type has the wrong runtime type.
  • Example:
BrUtils.new.cnpj.generate(prefix: 123)   # raises CnpjGen::TypeMismatchError
  • How to rescue it:
rescue CnpjGen::TypeMismatchError
  # generator type-contract violation

rescue TypeError
  # native type errors, including CnpjGen::TypeMismatchError
CnpjGen::InvalidArgumentCombinationError
  • Inheritance: CnpjGen::InvalidArgumentCombinationError < ArgumentError < StandardError (includes CnpjGen::Error)
  • Category: API misuse β€” mixed options and keywords on the generator API.
  • When it is raised: Raised by CnpjGen::CnpjGenerator / CnpjGen.cnpj_gen when both an options instance/Hash and any non-nil keyword are passed. (The CNPJ aggregator raises CnpjUtils::InvalidArgumentCombinationError for the same pattern on CnpjUtils#generate.)
  • Example:
CnpjGen::CnpjGenerator.new({ format: true }, prefix: '123')
# raises CnpjGen::InvalidArgumentCombinationError
  • How to rescue it:
rescue CnpjGen::InvalidArgumentCombinationError
  # generator invalid signature combination

rescue ArgumentError
  # native argument errors, including this one
CnpjGen::ValidationError
  • Inheritance: CnpjGen::ValidationError < CnpjGen::DomainError < RangeError < StandardError (includes CnpjGen::Error)
  • Category: Domain error β€” ineligible prefix or disallowed type.
  • When it is raised: Raised when prefix is a zeroed base/branch ID or 12 repeated digits, or when type is not 'alphabetic', 'alphanumeric', or 'numeric'.
  • Example:
BrUtils.new.cnpj.generate(type: 'boolean')   # raises CnpjGen::ValidationError
  • How to rescue it:
rescue CnpjGen::ValidationError
  # this exact domain validation failure

rescue CnpjGen::DomainError
  # RangeError-rooted domain failures from cnpj-gen
CnpjVal::DomainError
  • Inheritance: CnpjVal::DomainError < RangeError < StandardError (includes CnpjVal::Error)
  • Category: Domain error β€” ancestor for validator domain leaves.
  • When it is raised: Not raised directly; rescue target for CnpjVal::ValidationError.
  • Example: Prefer rescue CnpjVal::ValidationError or CnpjVal::DomainError.
  • How to rescue it:
rescue CnpjVal::DomainError
  # ValidationError and other DomainError subclasses from cnpj-val
CnpjVal::TypeMismatchError
  • Inheritance: CnpjVal::TypeMismatchError < TypeError < StandardError (includes CnpjVal::Error)
  • Category: API misuse β€” wrong type for CNPJ input or a validator option.
  • When it is raised: Raised when #is_valid / cnpj_val receives a value that is not a String or an Array of strings, or a validator option has the wrong type. Invalid CNPJ data returns false and does not raise.
  • Example:
BrUtils.new.cnpj.is_valid(12_345_678_000_198)   # raises CnpjVal::TypeMismatchError
BrUtils.new.cnpj.is_valid('00000000000000')     # => false (invalid data, no raise)
  • How to rescue it:
rescue CnpjVal::TypeMismatchError
  # validator type-contract violation

rescue TypeError
  # native type errors, including CnpjVal::TypeMismatchError
CnpjVal::InvalidArgumentCombinationError
  • Inheritance: CnpjVal::InvalidArgumentCombinationError < ArgumentError < StandardError (includes CnpjVal::Error)
  • Category: API misuse β€” mixed options and keywords on the validator API.
  • When it is raised: Raised by CnpjVal::CnpjValidator / CnpjVal.cnpj_val when both an options instance/Hash and any non-nil keyword are passed. (The CNPJ aggregator raises CnpjUtils::InvalidArgumentCombinationError for the same pattern on CnpjUtils#is_valid.)
  • Example:
CnpjVal.cnpj_val('98765432000198', { type: 'numeric' }, case_sensitive: false)
# raises CnpjVal::InvalidArgumentCombinationError
  • How to rescue it:
rescue CnpjVal::InvalidArgumentCombinationError
  # validator invalid signature combination

rescue ArgumentError
  # native argument errors, including this one
CnpjVal::ValidationError
  • Inheritance: CnpjVal::ValidationError < CnpjVal::DomainError < RangeError < StandardError (includes CnpjVal::Error)
  • Category: Domain error β€” disallowed validator type.
  • When it is raised: Raised when type is not 'alphanumeric' or 'numeric'.
  • Example:
BrUtils.new.cnpj.is_valid('91415732000793', type: 'boolean')   # raises CnpjVal::ValidationError
  • How to rescue it:
rescue CnpjVal::ValidationError
  # this exact domain validation failure

rescue CnpjVal::DomainError
  # RangeError-rooted domain failures from cnpj-val
CpfUtils::TypeMismatchError
  • Inheritance: CpfUtils::TypeMismatchError < TypeError < StandardError (includes CpfUtils::Error)
  • Category: API misuse β€” the caller passed a value of the wrong type.
  • When it is raised: Raised when CpfUtils.new receives a non-nil settings argument that is not a Hash.
  • Example:
CpfUtils.new('not-a-hash')   # raises CpfUtils::TypeMismatchError
CpfUtils.new(false)          # raises CpfUtils::TypeMismatchError (false is non-nil)
  • How to rescue it:
rescue CpfUtils::TypeMismatchError
  # CPF aggregator type-contract violation (not BrUtils::Error)

rescue TypeError
  # native type errors, including CpfUtils::TypeMismatchError
CpfUtils::InvalidArgumentCombinationError
  • Inheritance: CpfUtils::InvalidArgumentCombinationError < ArgumentError < StandardError (includes CpfUtils::Error)
  • Category: API misuse β€” the caller mixed mutually exclusive argument patterns.
  • When it is raised: Raised when CpfUtils.new receives both a non-nil settings Hash and any non-nil keyword, or when #format / #generate mix a non-nil options Hash/*Options with any non-nil keyword. #is_valid has no options path and does not raise this error.
  • Example:
BrUtils.new.cpf.format({ hidden: true }, dash_key: '|')
# raises CpfUtils::InvalidArgumentCombinationError
  • How to rescue it:
rescue CpfUtils::InvalidArgumentCombinationError
  # CPF aggregator invalid signature combination (not BrUtils::Error)

rescue ArgumentError
  # native argument errors, including CpfUtils::InvalidArgumentCombinationError
CnpjUtils::TypeMismatchError
  • Inheritance: CnpjUtils::TypeMismatchError < TypeError < StandardError (includes CnpjUtils::Error)
  • Category: API misuse β€” the caller passed a value of the wrong type.
  • When it is raised: Raised when CnpjUtils.new receives a non-nil settings argument that is not a Hash.
  • Example:
CnpjUtils.new('not-a-hash')   # raises CnpjUtils::TypeMismatchError
CnpjUtils.new(false)          # raises CnpjUtils::TypeMismatchError (false is non-nil)
  • How to rescue it:
rescue CnpjUtils::TypeMismatchError
  # CNPJ aggregator type-contract violation (not BrUtils::Error)

rescue TypeError
  # native type errors, including CnpjUtils::TypeMismatchError
CnpjUtils::InvalidArgumentCombinationError
  • Inheritance: CnpjUtils::InvalidArgumentCombinationError < ArgumentError < StandardError (includes CnpjUtils::Error)
  • Category: API misuse β€” the caller mixed mutually exclusive argument patterns.
  • When it is raised: Raised when CnpjUtils.new, #format, #generate, #is_valid, or the class helpers receive both a non-nil settings/options Hash (or options instance) and any non-nil keyword at the same time.
  • Example:
BrUtils.new.cnpj.format({ hidden: true }, slash_key: '|')
# raises CnpjUtils::InvalidArgumentCombinationError
  • How to rescue it:
rescue CnpjUtils::InvalidArgumentCombinationError
  # CNPJ aggregator invalid signature combination (not BrUtils::Error)

rescue ArgumentError
  # native argument errors, including CnpjUtils::InvalidArgumentCombinationError

Bundled packages

Package Main resources README
cpf-utilities CpfUtils, CpfFormatter, CpfGenerator, CpfValidator, CpfFmt.cpf_fmt, CpfGen.cpf_gen, CpfVal.cpf_val docs
cnpj-utilities CnpjUtils, CnpjFormatter, CnpjGenerator, CnpjValidator, CnpjFmt.cnpj_fmt, CnpjGen.cnpj_gen, CnpjVal.cnpj_val docs

All of the above are pulled in as dependencies of br-utilities. Interactive demos: CPF and CNPJ.

Contribution & Support

We welcome contributions! Please see our Contributing Guidelines for details. If you find this project helpful, please consider:

License

This project is licensed under the MIT License β€” see the LICENSE file for details.

Changelog

See CHANGELOG for a list of changes and version history.


Made with ❀️ by Lacus Solutions