Module: Genny::Array

Defined in:
lib/genny/array.rb

Class Method Summary collapse

Class Method Details

.genny(opts = {}) ⇒ Array

Generates an array of items of the types specified.

Examples:

No classes specified, can only return an empty array

Genny::Array.genny
# => []

Specifying classes

Genny::Array.genny(items: [Genny::Integer, JSONSchema.new("type" => "string", "format" => "ipv4")])
# => [739, "183.16.22.90", 87]

Parameters:

  • opts (Hash) (defaults to: {})

    Options for the generator

Options Hash (opts):

  • :items (Array<#genny>, #genny)

    The items which should be used to populate the array

  • :minItems (Integer) — default: 1

    The fewest number of items the array should have

  • :maxItems (Integer) — default: 5

    The largest number of items the array should have

Returns:

Raises:

  • RuntimeError if no :items given and minItems > 0

  • RuntimeError if :maxItems is lower than :minItems



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/genny/array.rb', line 22

def self.genny(opts = {})
  opts = Genny.symbolize(opts)
  opts[:items] = opts[:items].is_a?(::Array) ? opts[:items] : [opts[:items]].compact
  raise ArgumentError, "classes must be an array" unless opts[:items].respond_to?(:select)
  items = opts[:items].select { |item| item.respond_to?(:genny) }.dup
  if items.empty?
    raise "No items given, cannot populate the array." unless opts[:minItems].to_i == 0
    return []
  end
  min_count = opts[:minItems] || 1
  max_count = opts[:maxItems] || [min_count, 5].max
  raise "maxItems is lower than minItems" if max_count < min_count
  count = Random.rand(max_count - min_count + 1) + min_count
  generated = []
  count.times do
    break if items.empty?
    i = Random.rand(0...items.size)
    generated.push(items[i].genny)
    items.delete_at(i) if opts[:uniqueItems]
  end
  generated
end