Class: Synthra::Scenarios::FixtureDefinition

Inherits:
Object
  • Object
show all
Defined in:
lib/synthra/scenarios.rb

Overview

A fixture definition

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, schema = nil, **options, &block) ⇒ FixtureDefinition

Returns a new instance of FixtureDefinition.



209
210
211
212
213
214
# File 'lib/synthra/scenarios.rb', line 209

def initialize(name, schema = nil, **options, &block)
  @name = name
  @schema = schema
  @options = options
  @block = block
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



207
208
209
# File 'lib/synthra/scenarios.rb', line 207

def block
  @block
end

#nameObject (readonly)

Returns the value of attribute name.



207
208
209
# File 'lib/synthra/scenarios.rb', line 207

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



207
208
209
# File 'lib/synthra/scenarios.rb', line 207

def options
  @options
end

#schemaObject (readonly)

Returns the value of attribute schema.



207
208
209
# File 'lib/synthra/scenarios.rb', line 207

def schema
  @schema
end

Instance Method Details

#build(context) ⇒ Object



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/synthra/scenarios.rb', line 216

def build(context)
  # Resolve references in options
  resolved_options = resolve_references(context)

  # Generate base data
  if @schema
    schema_obj = Synthra.registry.schema(@schema.to_s)
    # :nocov: registry.schema raises KeyError for a missing schema, so this guard is unreachable
    raise ArgumentError, "Unknown schema: #{@schema}" unless schema_obj
    # :nocov:

    data = schema_obj.generate(
      seed: context.seed,
      overrides: resolved_options
    )
  else
    data = resolved_options
  end

  # Apply customization block
  data = @block.call(data, context) if @block

  data
end

#resolve_references(context) ⇒ Object (private)



243
244
245
246
247
248
249
250
251
# File 'lib/synthra/scenarios.rb', line 243

def resolve_references(context)
  resolved = {}

  @options.each do |key, value|
    resolved[key.to_s] = resolve_value(value, context)
  end

  resolved
end

#resolve_value(value, context) ⇒ Object (private)



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/synthra/scenarios.rb', line 253

def resolve_value(value, context)
  case value
  when Symbol
    # Reference to another fixture
    context[value] || value.to_s
  when Proc
    value.call(context)
  when Hash
    value.transform_values { |v| resolve_value(v, context) }
  when Array
    value.map { |v| resolve_value(v, context) }
  else
    value
  end
end