Module: PostalCodesSearch

Defined in:
lib/postal-codes-search.rb

Overview

Class module that handles all searching methods for postal codes

Constant Summary collapse

VERSION =
'1.1'
SUPPORTED_COUNTRIES =
i[us ca].freeze

Class Method Summary collapse

Class Method Details

.attribute_present(attr) ⇒ Object



12
13
14
# File 'lib/postal-codes-search.rb', line 12

def attribute_present(attr)
  !(attr.nil? || attr.empty?)
end

.dataObject



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/postal-codes-search.rb', line 35

def data
  data = []
  current_path = File.dirname(__FILE__)
  SUPPORTED_COUNTRIES.each do |country_code|
    data_path = File.join(current_path, 'source', "#{country_code}_postal_codes.yml")
    country_data = YAML.safe_load(File.open(data_path))

    data += country_data
  end
  data
end

.data_sourceObject



47
48
49
50
51
# File 'lib/postal-codes-search.rb', line 47

def data_source
  @data_source ||= begin
    data
  end
end

.find(term) ⇒ Object



30
31
32
33
# File 'lib/postal-codes-search.rb', line 30

def find(term)
  term = term.to_s
  find_by(code: term, country: term, county: term, city: term, state: term)
end

.find_by(code: nil, country: nil, county: nil, city: nil, state: nil) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/postal-codes-search.rb', line 20

def find_by(code: nil, country: nil, county: nil, city: nil, state: nil)
  data_source.select do |postal_code|
    selectable?(code, postal_code['postal_code']) ||
      selectable?(country, postal_code['country']) ||
      selectable?(county, postal_code['county']) ||
      selectable?(city, postal_code['city']) ||
      selectable?(state, postal_code['state'])
  end
end

.loadObject



53
54
55
# File 'lib/postal-codes-search.rb', line 53

def load
  data_source
end

.selectable?(term, value) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/postal-codes-search.rb', line 16

def selectable?(term, value)
  attribute_present(term) && value && value.to_s.downcase.include?(term.to_s.downcase)
end