Sha256: 3aaa9c0ed7d8e641936d663f2c31ea576c8512eb8544b5d396aef340d51fe79d

Contents?: true

Size: 1.39 KB

Versions: 5

Compression:

Stored size: 1.39 KB

Contents

# encoding: UTF-8

# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0

require 'rest-client'
require 'json'
require 'yaml'

module TwitterCldr
  module Resources

    class PostalCodesImporter

      BASE_URL = 'http://i18napis.appspot.com/address/data/'

      # Arguments:
      #
      #   output_path - output directory for generated YAML file
      #
      def initialize(output_path)
        @output_path = output_path
      end

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

      private

      def load
        each_territory.each_with_object({}) do |territory, ret|
          next unless regex = get_regex_for(territory)

          ret[territory] = {
            regex: Regexp.compile(regex),
            ast: TwitterCldr::Utils::RegexpAst.dump(
              RegexpAstGenerator.generate(regex)
            )
          }
        end
      end

      def get_regex_for(territory)
        result = RestClient.get("#{BASE_URL}#{territory.to_s.upcase}")
        data = JSON.parse(result.body)
        data['zip']
      end

      def each_territory
        if block_given?
          TwitterCldr::Shared::Territories.all.each_pair do |territory, _|
            yield territory
          end
        else
          to_enum(__method__)
        end
      end

    end

  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
twitter_cldr-4.0.0 lib/twitter_cldr/resources/postal_codes_importer.rb
twitter_cldr-3.6.0 lib/twitter_cldr/resources/postal_codes_importer.rb
twitter_cldr-3.5.0 lib/twitter_cldr/resources/postal_codes_importer.rb
twitter_cldr-3.4.0 lib/twitter_cldr/resources/postal_codes_importer.rb
twitter_cldr-3.3.0 lib/twitter_cldr/resources/postal_codes_importer.rb