class RandomSet::Template

@api private

Attributes

generators[R]

Public Class Methods

new(templates) click to toggle source

Initialization & attributes

# File lib/random_set/template.rb, line 9
def initialize(templates)
  @hash       = templates.is_a?(Hash)
  @generators = resolve_generators(templates)
end

Public Instance Methods

count() click to toggle source
# File lib/random_set/template.rb, line 20
def count
  max = nil
  generators.each do |_key, generator|
    next unless generator && generator.respond_to?(:count)
    max = [ max.to_i, generator.count ].max
  end
  max
end
generate(count = self.count) click to toggle source

Generation

# File lib/random_set/template.rb, line 32
def generate(count = self.count)
  raise CannotInferCount, "no count was specified or could be inferred" unless count

  data = []
  count.times.each { data << generate_next(data) }
  data
end
hash?() click to toggle source
# File lib/random_set/template.rb, line 14
def hash?
  @hash
end

Private Instance Methods

create_generator(template) click to toggle source
# File lib/random_set/template.rb, line 61
def create_generator(template)
  case template
  when nil then nil
  when ->(t){ t.respond_to?(:next) } then template
  when ->(t){ t.respond_to?(:each) } then template.each
  when Proc then CustomGenerator.new(template)
  else raise UnsupportedTemplate, "cannot create a generator for a template of class #{template.class}"
  end
end
generate_next(data) click to toggle source
# File lib/random_set/template.rb, line 71
def generate_next(data)
  item = hash? ? {} : []
  generators.each do |key, generator|
    begin
      item[key] = generator ? generator.next : nil
    rescue StopIteration
      # If some enumerator came to the end, we just leave the rest of the keys blank.
      item[key] = nil
    end
  end
  item
end
resolve_generators(templates) click to toggle source

Support

# File lib/random_set/template.rb, line 45
def resolve_generators(templates)
  hash = {}

  process = proc do |key, template|
    hash[key] = create_generator(template)
  end

  if hash?
    templates.each &process
  else
    templates.each_with_index { |template, index| process[index, template] }
  end

  hash
end