Class: Context

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timeout: nil) ⇒ Context

Returns a new instance of Context.



4
5
6
7
8
9
10
11
12
13
14
# File 'lib/context.rb', line 4

def initialize(timeout: nil)
  @timeout = timeout
  @canceled = false
  @mutex = Mutex.new
  @condition = ConditionVariable.new

  # Start a timer if a timeout is specified
  if @timeout
    @start_time = Time.now
  end
end

Instance Attribute Details

#canceledObject (readonly)

Returns the value of attribute canceled.



2
3
4
# File 'lib/context.rb', line 2

def canceled
  @canceled
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



2
3
4
# File 'lib/context.rb', line 2

def timeout
  @timeout
end

Instance Method Details

#cancelObject



16
17
18
19
20
21
# File 'lib/context.rb', line 16

def cancel
  @mutex.synchronize do
    @canceled = true
    @condition.broadcast
  end
end

#resetObject



41
42
43
44
45
46
# File 'lib/context.rb', line 41

def reset
  @mutex.synchronize do
    @canceled = false
    @start_time = Time.now if @timeout
  end
end

#timed_out?Boolean

Returns:

  • (Boolean)


23
24
25
26
27
28
# File 'lib/context.rb', line 23

def timed_out?
  return false unless @timeout

  # Check the elapsed time without locking the mutex
  Time.now - @start_time > @timeout
end

#wait(&block) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/context.rb', line 30

def wait(&block)
  reset # Reset the context state before waiting
  loop do
    break if block.call
    if timed_out?
      raise StandardError.new("Operation timed out after #{timeout} seconds")
    end
    sleep(0.1) # Sleep briefly to avoid busy-waiting
  end
end