Class: AsyncProxy::ComputedProxy

Inherits:
ObjectProxy show all
Defined in:
lib/computed_proxy.rb

Overview

a specialization of ObjectProxy to be used when the wraped value is dependent on another async proxy and a computation (a block)

will be automatically created by calling a method or when_ready in any async object

the user should not directly create objects of this class

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from ObjectProxy

#each, #map, #register_callback, #to_s, #when_ready

Constructor Details

#initialize(callable, proc, trace_name = nil) ⇒ ComputedProxy

Returns a new instance of ComputedProxy.



17
18
19
20
21
22
# File 'lib/computed_proxy.rb', line 17

def initialize(callable, proc, trace_name = nil)
  @callable   = callable
  @proc       = proc
  @trace_name = trace_name
  @callbacks = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class AsyncProxy::ObjectProxy

Instance Attribute Details

#callableObject (readonly)

Returns the value of attribute callable.



13
14
15
# File 'lib/computed_proxy.rb', line 13

def callable
  @callable
end

#procObject (readonly)

Returns the value of attribute proc.



14
15
16
# File 'lib/computed_proxy.rb', line 14

def proc
  @proc
end

#trace_nameObject (readonly)

Returns the value of attribute trace_name.



15
16
17
# File 'lib/computed_proxy.rb', line 15

def trace_name
  @trace_name
end

Instance Method Details

#asyncObject



28
29
30
# File 'lib/computed_proxy.rb', line 28

def async
  self
end

#launch_computationObject



46
47
48
49
50
51
52
# File 'lib/computed_proxy.rb', line 46

def launch_computation
  @thread = Thread.new do
    @result = @proc.call(@callable.sync)
    @ready = true
    run_callbacks
  end
end

#ready?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/computed_proxy.rb', line 24

def ready?
  @ready
end

#sync(options = {}) ⇒ Object

waits for the computation to finish and returns the actual result

optional arguments:

- timeout: the maximum number of seconds that the computation can take.


37
38
39
40
41
42
43
44
# File 'lib/computed_proxy.rb', line 37

def sync(options = {})
  if options[:timeout]
    SystemTimer.timeout_after(options[:timeout]){wait_for_computation}
  else
    wait_for_computation
  end
  @result
end

#wait_for_computationObject



54
55
56
57
# File 'lib/computed_proxy.rb', line 54

def wait_for_computation
  callable.sync # ensures the callable has finished and run its callbacks
  @thread.join unless @done
end