Sha256: 195ade941e1285888dc3f381ec0e6353756902cc778335510d3101af75df263f

Contents?: true

Size: 1.09 KB

Versions: 63

Compression:

Stored size: 1.09 KB

Contents

# encoding: UTF-8

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

require 'set'

module TwitterCldr
  module Shared
    class PostalCodeGenerator

      SAMPLE_MULTIPLIER = 4

      def initialize(regexp_ast)
        @regexp_generator = TwitterCldr::Utils::RegexpSampler.new(regexp_ast)
      end

      def generate
        clean_result(@regexp_generator.generate)
      end

      def sample(sample_size = 1)
        sample_set = Set.new
        counter = 1

        until sample_set.size == sample_size
          sample = generate
          sample_set << sample unless sample.empty?
          counter += 1

          # Stop if the number of attempted generations is
          # n times more than requested. Some territories only
          # have one postal code, so if the user asks for 10
          # they'll get an infinite loop.
          break if counter > sample_size * SAMPLE_MULTIPLIER
        end

        sample_set.to_a
      end

      private

      # remove spaces that trail a dash
      def clean_result(str)
        str.gsub(/- /, '-')
      end

    end
  end
end

Version data entries

63 entries across 63 versions & 3 rubygems

Version Path
twitter_cldr-6.13.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.12.1 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.12.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.11.5 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.11.4 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.11.3 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.11.2 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.11.1 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.11.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.10.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.9.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.8.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.7.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.6.2 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.6.1 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.6.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.5.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.4.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.3.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-6.2.0 lib/twitter_cldr/shared/postal_code_generator.rb