Class: Crspec::ExecutionContext

Inherits:
Object
  • Object
show all
Defined in:
lib/crspec/execution_context.rb

Constant Summary collapse

STORAGE_KEY =
:crspec_execution_context

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(example_id, metadata = {}, parent = nil) ⇒ ExecutionContext

Returns a new instance of ExecutionContext.



26
27
28
29
30
31
32
# File 'lib/crspec/execution_context.rb', line 26

def initialize(example_id,  = {}, parent = nil)
  @example_id = example_id
  @metadata = .freeze
  @parent = parent
  @memoized_values = {}
  @monitor = Monitor.new
end

Instance Attribute Details

#example_idObject (readonly)

Returns the value of attribute example_id.



10
11
12
# File 'lib/crspec/execution_context.rb', line 10

def example_id
  @example_id
end

#metadataObject (readonly)

Returns the value of attribute metadata.



10
11
12
# File 'lib/crspec/execution_context.rb', line 10

def 
  @metadata
end

#parentObject (readonly)

Returns the value of attribute parent.



10
11
12
# File 'lib/crspec/execution_context.rb', line 10

def parent
  @parent
end

Class Method Details

.currentObject



12
13
14
# File 'lib/crspec/execution_context.rb', line 12

def self.current
  Fiber[STORAGE_KEY] ||= new(SecureRandom.uuid)
end

.isolate(example_id, metadata = {}) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/crspec/execution_context.rb', line 16

def self.isolate(example_id,  = {})
  parent_context = Fiber[STORAGE_KEY]
  new_context = new(example_id, , parent_context)

  # Fiber storage inheritance preserves context while isolating mutations
  Fiber.new(storage: { STORAGE_KEY => new_context }) do
    yield new_context
  end.resume
end

Instance Method Details

#[](key) ⇒ Object



44
45
46
47
48
# File 'lib/crspec/execution_context.rb', line 44

def [](key)
  @monitor.synchronize do
    @memoized_values[key]
  end
end

#[]=(key, value) ⇒ Object



50
51
52
53
54
# File 'lib/crspec/execution_context.rb', line 50

def []=(key, value)
  @monitor.synchronize do
    @memoized_values[key] = value
  end
end

#fetch_memoized(key, &block) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/crspec/execution_context.rb', line 34

def fetch_memoized(key, &block)
  return @memoized_values[key] if @memoized_values.key?(key)

  @monitor.synchronize do
    return @memoized_values[key] if @memoized_values.key?(key)

    @memoized_values[key] = yield
  end
end

#reset!Object



56
57
58
59
60
# File 'lib/crspec/execution_context.rb', line 56

def reset!
  @monitor.synchronize do
    @memoized_values.clear
  end
end