Class: AsyncMethods::Proxy

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

Overview

The proxy object does all the heavy lifting.

Constant Summary collapse

PROTECTED_METHODS =

These methods we don’t want to override. All other existing methods will be redefined.

%w(initialize method_missing __proxy_result__ __proxy_loaded__ __send__ __id__ object_id)

Instance Method Summary collapse

Constructor Details

#initialize(obj, method, args = [], &block) ⇒ Proxy

Returns a new instance of Proxy.



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/async_methods/async_methods.rb', line 73

def initialize (obj, method, args = [], &block)
  @proxy_result = nil
  @proxy_exception = nil
  @thread = Thread.new do
    begin
      if obj && method
        @proxy_result = obj.send(method, *args, &block)
      else
        @proxy_result = block.call
      end
    rescue Exception => e
      @proxy_exception = e
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object

All missing methods are proxied to the original result object.



102
103
104
# File 'lib/async_methods/async_methods.rb', line 102

def method_missing (method, *args, &block)
  __proxy_result__.send(method, *args, &block)
end

Instance Method Details

#__proxy_loaded__Object



97
98
99
# File 'lib/async_methods/async_methods.rb', line 97

def __proxy_loaded__
  !(@thread && @thread.alive?)
end

#__proxy_result__Object

Get the result of the original method call. The original method will only be called once.

Raises:

  • (@proxy_exception)


90
91
92
93
94
95
# File 'lib/async_methods/async_methods.rb', line 90

def __proxy_result__
  @thread.join if @thread && @thread.alive?
  @thread = nil
  raise @proxy_exception if @proxy_exception
  return @proxy_result
end