Class: Synthra::Personas::PersonaContext

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

Overview

Runtime context for persona application

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(persona) ⇒ PersonaContext

Returns a new instance of PersonaContext.



275
276
277
278
# File 'lib/synthra/personas.rb', line 275

def initialize(persona)
  @persona = persona
  @generated = {}
end

Instance Attribute Details

#personaObject (readonly)

Returns the value of attribute persona.



273
274
275
# File 'lib/synthra/personas.rb', line 273

def persona
  @persona
end

Instance Method Details

#apply(&block) ⇒ Object



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/synthra/personas.rb', line 280

def apply(&block)
  # Run before hooks
  @persona.instance_variable_get(:@before_hooks).each { |h| instance_exec(&h) }

  # Set thread-local context
  old_context = Thread.current[:synthra_persona]
  Thread.current[:synthra_persona] = self

  # Yield self to the block instead of instance_eval to preserve caller's context
  result = block.call(self)

  # Run after hooks
  @persona.instance_variable_get(:@after_hooks).each { |h| instance_exec(&h) }

  result
ensure
  Thread.current[:synthra_persona] = old_context
end

#generate(schema_name, **options) ⇒ Object

Generate data with persona settings



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/synthra/personas.rb', line 300

def generate(schema_name, **options)
  schema = Synthra.registry.schema(schema_name.to_s)

  merged_options = {
    mode: @persona.generation_mode,
    seed: @persona.generation_seed,
    overrides: @persona.overrides_for(schema_name.to_s)
  }.merge(options)

  data = schema.generate(**merged_options)

  # Apply transforms
  @persona.transforms.each do |transform|
    if transform[:schema].nil? || transform[:schema] == schema_name.to_s
      data = transform[:block].call(data, self)
    end
  end

  @generated[schema_name.to_s] = data
  data
end