Class: Braintrust::Contrib::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/braintrust/contrib/context.rb

Overview

Per-instance or per-class configuration context. Allows attaching generic configuration to specific objects or classes.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ Context

Returns a new instance of Context.

Parameters:

  • options (Hash)

    Configuration options



35
36
37
# File 'lib/braintrust/contrib/context.rb', line 35

def initialize(**options)
  @options = options
end

Class Method Details

.from(target) ⇒ Context?

Retrieve context from a target.

Parameters:

  • target (Object)

    The object to retrieve context from

Returns:

  • (Context, nil)

    The context if found, nil otherwise



30
31
32
# File 'lib/braintrust/contrib/context.rb', line 30

def self.from(target)
  target&.instance_variable_get(:@braintrust_context)
end

.set!(target, **options) ⇒ Context?

Set or update context on a target object. Creates a new context if one doesn’t exist, or updates existing context.

Parameters:

  • target (Object)

    The object to attach context to

  • options (Hash)

    Configuration options to store

Returns:

  • (Context, nil)

    The existing context if updated, nil if created new or options empty



13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/braintrust/contrib/context.rb', line 13

def self.set!(target, **options)
  return nil if options.empty?

  if (ctx = from(target))
    # Update existing context
    options.each { |k, v| ctx[k] = v }
  else
    # Create and attach new context
    target.instance_variable_set(:@braintrust_context, new(**options))
  end

  ctx
end

Instance Method Details

#[](key) ⇒ Object



39
40
41
# File 'lib/braintrust/contrib/context.rb', line 39

def [](key)
  @options[key]
end

#[]=(key, value) ⇒ Object



43
44
45
# File 'lib/braintrust/contrib/context.rb', line 43

def []=(key, value)
  @options[key] = value
end

#fetch(key, default) ⇒ Object

Get an option value with a default fallback.

Parameters:

  • key (Symbol, String)

    The option key

  • default (Object)

    The default value if key not found

Returns:

  • (Object)

    The option value, or default if not found



51
52
53
# File 'lib/braintrust/contrib/context.rb', line 51

def fetch(key, default)
  @options.fetch(key, default)
end