Class: RandomSet::Template

Inherits:
Object
  • Object
show all
Defined in:
lib/random_set/template.rb

Overview

A template for the random set.

Defined Under Namespace

Classes: CustomGenerator

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(templates) ⇒ Template

Returns a new instance of Template.



7
8
9
10
# File 'lib/random_set/template.rb', line 7

def initialize(templates)
  @hash       = templates.is_a?(Hash)
  @generators = resolve_generators(templates)
end

Instance Attribute Details

#generatorsObject (readonly)



42
43
44
# File 'lib/random_set/template.rb', line 42

def generators
  @generators
end

Instance Method Details

#countObject

Gives a count for the items in this template. If no count can be inferred, nil is returned.



45
46
47
48
49
50
51
52
# File 'lib/random_set/template.rb', line 45

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

#create_generator(template) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/random_set/template.rb', line 32

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(count = self.count) ⇒ Object

Raises:



54
55
56
57
58
59
60
# File 'lib/random_set/template.rb', line 54

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

#generate_next(data) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/random_set/template.rb', line 62

def generate_next(data)
  item = hash? ? {} : []
  generators.each do |key, generator|
    begin
      item[key] = generator.try(:next)
    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

#hash?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/random_set/template.rb', line 12

def hash?
  @hash
end

#resolve_generators(templates) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/random_set/template.rb', line 16

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