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-4.1.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-4.0.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.6.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.5.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.4.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.3.0 lib/twitter_cldr/shared/postal_code_generator.rb
solidus_backend-1.0.0.pre3 vendor/bundle/gems/twitter_cldr-3.2.1/lib/twitter_cldr/shared/postal_code_generator.rb
solidus_backend-1.0.0.pre2 vendor/bundle/gems/twitter_cldr-3.2.1/lib/twitter_cldr/shared/postal_code_generator.rb
solidus_backend-1.0.0.pre vendor/bundle/gems/twitter_cldr-3.1.2/lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.2.1 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.2.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.1.2 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.1.1 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.1.0 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.0.10 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.0.9 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.0.8 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.0.7 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.0.6 lib/twitter_cldr/shared/postal_code_generator.rb
twitter_cldr-3.0.5 lib/twitter_cldr/shared/postal_code_generator.rb