Class: AsyncMethods::Proxy
- Inherits:
-
Object
- Object
- AsyncMethods::Proxy
- 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 __proxy_result__ __proxy_loaded__ method_missing __send__ object_id)
Instance Method Summary collapse
- #__proxy_loaded__ ⇒ Object
-
#__proxy_result__ ⇒ Object
Get the result of the original method call.
-
#initialize(obj, method, args = [], &block) ⇒ Proxy
constructor
A new instance of Proxy.
-
#method_missing(method, *args, &block) ⇒ Object
All missing methods are proxied to the original result object.
Constructor Details
#initialize(obj, method, args = [], &block) ⇒ Proxy
Returns a new instance of Proxy.
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/async_methods/async_methods.rb', line 59 def initialize (obj, method, args = [], &block) # Override already defined methods on Object to proxy them to the result object methods.each do |m| eval "def self.#{m} (*args, &block); __proxy_result__.send(:#{m}, *args, &block); end" unless PROTECTED_METHODS.include?(m.to_s) end @thread = Thread.new do begin if obj and method @proxy_result = obj.send(method, *args, &block) else @proxy_result = block.call end rescue Object => 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.
91 92 93 |
# File 'lib/async_methods/async_methods.rb', line 91 def method_missing (method, *args, &block) __proxy_result__.send(method, *args, &block) end |
Instance Method Details
#__proxy_loaded__ ⇒ Object
86 87 88 |
# File 'lib/async_methods/async_methods.rb', line 86 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.
79 80 81 82 83 84 |
# File 'lib/async_methods/async_methods.rb', line 79 def __proxy_result__ @thread.join if @thread && @thread.alive? @thread = nil raise @proxy_exception if @proxy_exception return @proxy_result end |