Class: AsyncCall

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

Overview

Asynchronously calls a method

Constant Summary collapse

DEFAULT_TIMEOUT =
5.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj, method, *args, &block) ⇒ AsyncCall

Returns a new instance of AsyncCall.



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/capybarbecue/async_call.rb', line 10

def initialize(obj, method, *args, &block)
  @obj, @method, @args, @block = obj, method, args, block
  @ready = false
  @response = nil
  @exception = nil
  @thread = Thread.new do
    begin
      respond_with obj.send(method, *args, &block)
    rescue Exception => e
      respond_with_exception e
    end
  end
end

Instance Attribute Details

#readyObject (readonly) Also known as: ready?

Returns the value of attribute ready.



6
7
8
# File 'lib/capybarbecue/async_call.rb', line 6

def ready
  @ready
end

#threadObject (readonly)

Returns the value of attribute thread.



5
6
7
# File 'lib/capybarbecue/async_call.rb', line 5

def thread
  @thread
end

#to_sObject (readonly)

Returns the value of attribute to_s.



7
8
9
# File 'lib/capybarbecue/async_call.rb', line 7

def to_s
  @to_s
end

Instance Method Details

#kill!Object



42
43
44
# File 'lib/capybarbecue/async_call.rb', line 42

def kill!
  @thread.kill
end

#wait_for_response(timeout = DEFAULT_TIMEOUT) ⇒ Object

If a block is passed, it will be called repeatedly until a response comes in



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/capybarbecue/async_call.rb', line 25

def wait_for_response(timeout=DEFAULT_TIMEOUT)
  started_at = Time.now
  while Time.now - started_at < timeout.seconds && !ready?
    yield if block_given?
    # It feels dangerous not to sleep here... keep a pulse on this (sleep causes performance problems)
    Thread.pass
  end
  kill! and raise Timeout::Error.new('Timeout expired before response received') unless ready?
  if @exception.present?
    # Add the backtrace from this thread to make it useful
    backtrace = @exception.backtrace + Kernel.caller
    @exception.set_backtrace(backtrace)
    raise @exception
  end
  @response
end