Module: BrazilianUtils::StateUtils

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

Overview

Utilities for looking up Brazil's 27 federative units (states + the Distrito Federal): code (sigla), name, region and IBGE code, sourced from the IBGE Localidades API.

Constant Summary collapse

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

Class Method Summary collapse

Class Method Details

.get_by_ibge_code(code) ⇒ Hash?

Returns the state whose 2-digit IBGE code (cUF) matches code.

Parameters:

  • code (String, Integer)

Returns:

  • (Hash, nil)


53
54
55
56
57
58
59
60
61
# File 'lib/brazilian-utils/state-utils.rb', line 53

def self.get_by_ibge_code(code)
  return nil if code.nil?

  str = code.to_s.strip
  return nil unless str.match?(/\A\d+\z/)

  row = load_data.find { |r| r['ibgeCode'] == str.to_i }
  row && to_symbolized(row)
end

.get_code_by_name(name) ⇒ String?

Returns the two-letter code (sigla) of a state from its full name.

Parameters:

  • name (String)

Returns:

  • (String, nil)


67
68
69
70
71
72
73
74
75
# File 'lib/brazilian-utils/state-utils.rb', line 67

def self.get_code_by_name(name)
  return nil unless name.is_a?(String)

  normalized = normalize_name(name)
  return nil if normalized.empty?

  row = load_data.find { |r| normalize_name(r['name']) == normalized }
  row && row['code']
end

.get_name_by_code(code) ⇒ String?

Returns the full name of a state from its two-letter code (sigla).

Parameters:

  • code (String)

Returns:

  • (String, nil)


81
82
83
84
85
86
87
88
89
# File 'lib/brazilian-utils/state-utils.rb', line 81

def self.get_name_by_code(code)
  return nil unless code.is_a?(String)

  normalized = code.strip.upcase
  return nil if normalized.empty?

  row = load_data.find { |r| r['code'] == normalized }
  row && row['name']
end

.get_timezone(state_code) ⇒ String?

Returns the IANA time zone of a state (the zone of its capital).

Parameters:

  • state_code (String)

Returns:

  • (String, nil)


95
96
97
98
99
100
101
102
103
# File 'lib/brazilian-utils/state-utils.rb', line 95

def self.get_timezone(state_code)
  return nil unless state_code.is_a?(String)

  normalized = state_code.strip.upcase
  return nil if normalized.empty?

  row = load_data.find { |r| r['code'] == normalized }
  row && row['timezone']
end

.list ⇒ Array<Hash>

Returns the 27 Brazilian federative units, sorted by name (pt-BR collation, approximated by comparing accent-stripped names).

Returns:

  • (Array<Hash>) —

    Each entry has :code, :name, :regionCode, :regionName and :ibgeCode.



43
44
45
46
47
# File 'lib/brazilian-utils/state-utils.rb', line 43

def self.list
  load_data
    .sort_by { |row| normalize_name(row['name']) }
    .map { |row| to_symbolized(row) }
end