Module: PostalCode

Defined in:
lib/postal_code.rb

Constant Summary collapse

VERSION =
'0.4.0'
CityOffset =
0
StateOffset =
1
DB =
File.join File.dirname(__FILE__), '..', 'db', 'US.tsv'
FS =

field separator

"\t"
RS =

record separator

"\n"

Class Method Summary collapse

Class Method Details

.city(postal_code) ⇒ Object

Return the city for the given postal code.


36
37
38
# File 'lib/postal_code.rb', line 36

def self.city postal_code
  fetch(postal_code)[CityOffset]
end

.clear_cacheObject

Clear the in-memory postal code cache.


29
30
31
# File 'lib/postal_code.rb', line 29

def self.clear_cache
  @cache.clear
end

.load_cacheObject

Load the entire postal code database into memory.


16
17
18
19
20
21
22
23
24
# File 'lib/postal_code.rb', line 16

def self.load_cache
  open(DB) do |db|
    db.each_line do |line|
      line.rstrip!  # remove RS
      pcode, city, state = line.split(FS)
      @cache[pcode] = [city, state]
    end
  end
end

.state(postal_code) ⇒ Object

Return the state (two-letter abbreviation) for the given postal code.


43
44
45
# File 'lib/postal_code.rb', line 43

def self.state postal_code
  fetch(postal_code)[StateOffset]
end

.valid_format?(postal_code) ⇒ Boolean

Postal codes must be strings because:

  1. Postal codes are not calculable, therefore should not be numeric.

  2. A postal code with a leading zero would be an octal. However, 08880 is an invalid octal numeric, yet a valid postal code.

Returns:

  • (Boolean)

53
54
55
56
57
58
59
# File 'lib/postal_code.rb', line 53

def self.valid_format? postal_code
  unless postal_code.is_a? String
    raise(TypeError, "postal code must be a string")
  end

  (postal_code =~ /^\d{5}(-\d{4})?$/) ? true : false
end