require 'json' module Eco module Data module Random class Values attr_accessor :multiple, :unique attr_reader :options, :weights, :options_weight, :quantity attr_reader :generator, :generator_config def initialize(init = {}) @multiple = init.fetch('multiple', false) @unique = init.fetch('unique', true) self.quantity = init.fetch('quantity', nil) @options_weight = init.fetch('options_weight', nil) @options = init.fetch('options', @options_weight&.keys) @weights = @options_weight&.values @generator_config = init.fetch('generator_config', { "decimals" => 0 }) if @weights @generator_config['weights'] = @weights unless @generator_config.key?('weights') @generator_config['balance'] = 'forged' unless @generator_config.key?('balance') else case when @options&.instance_of?(Array) @generator_config['weights'] = @weights unless @generator_config.key?('weights') end end @generator = Distribution.new(@generator_config) @random = ::Random.new end def quantity=(num_or_range) # attr_writer val = num_or_range case when val.is_a?(Numeric) num = val.round rng = (num..num) when val.instance_of?(Range) rng = val else rng = (0..1) end @quantity = rng end def generate if @multiple quantity = @random.rand(@quantity) value = [] quantity.times { val = @unique? generate_option(exclude: value): generate_option value.push(val) } value = value.uniq if @unique else value = generate_option end return value end def generate_option(exclude: []) case when @options&.instance_of?(Array) val = @options[@generator.generate] else puts "something bad with @options" end #exclude_aux = Marshal.load(Marshal::dump(exclude)) exclude_aux = JSON.parse(exclude.to_json) exclude_aux.pop val = generate_option(exclude: exclude_aux) if exclude.include?(val) return val end end end end end