Class: TwitterCldr::Resources::PostalCodesImporter

Inherits:
Object
  • Object
show all
Defined in:
lib/twitter_cldr/resources/postal_codes_importer.rb

Constant Summary collapse

POSTAL_CODES_PATH =
File.join('common', 'supplemental', 'postalCodeData.xml')

Instance Method Summary collapse

Constructor Details

#initialize(input_path, output_path) ⇒ PostalCodesImporter

Arguments:

input_path  - path to a directory containing CLDR data
output_path - output directory for generated YAML file


22
23
24
25
# File 'lib/twitter_cldr/resources/postal_codes_importer.rb', line 22

def initialize(input_path, output_path)
  @input_path  = input_path
  @output_path = output_path
end

Instance Method Details

#importObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/twitter_cldr/resources/postal_codes_importer.rb', line 27

def import
  TwitterCldr::Resources.download_cldr_if_necessary(@input_path)

  doc = File.open(File.join(@input_path, POSTAL_CODES_PATH)) { |file| Nokogiri::XML(file) }

  postal_codes = doc.xpath('//postCodeRegex').inject({}) do |memo, node|
    memo[node.attr('territoryId').downcase.to_sym] = Regexp.new(node.text); memo
  end

  postal_codes = Hash[postal_codes.sort_by(&:first)]

  postal_codes = postal_codes.each_with_object({}) do |(territory, regex), memo|
    memo[territory] = {
      :regex => regex,
      :ast => TwitterCldr::Utils::RegexpAst.dump(
        RegexpAstGenerator.generate(regex.source)
      )
    }
  end

  File.open(File.join(@output_path, 'postal_codes.yml'), 'w') do |output|
    output.write(YAML.dump(postal_codes))
  end
end