Class: LazyMethods::Proxy
- Inherits:
-
Object
- Object
- LazyMethods::Proxy
- Defined in:
- lib/lazy_methods/lazy_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
Helper method that indicates if the proxy has loaded the original method results yet.
-
#__proxy_result__ ⇒ Object
Get the result of the original method call.
-
#initialize(obj, method, args = nil, &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 = nil, &block) ⇒ Proxy
Returns a new instance of Proxy.
54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/lazy_methods/lazy_methods.rb', line 54 def initialize (obj, method, args = nil, &block) @object = obj @method = method @args = args || [] @block = 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 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.
78 79 80 |
# File 'lib/lazy_methods/lazy_methods.rb', line 78 def method_missing (method, *args, &block) __proxy_result__.send(method, *args, &block) end |
Instance Method Details
#__proxy_loaded__ ⇒ Object
Helper method that indicates if the proxy has loaded the original method results yet.
73 74 75 |
# File 'lib/lazy_methods/lazy_methods.rb', line 73 def __proxy_loaded__ !!defined?(@proxy_result) end |
#__proxy_result__ ⇒ Object
Get the result of the original method call. The original method will only be called once.
67 68 69 70 |
# File 'lib/lazy_methods/lazy_methods.rb', line 67 def __proxy_result__ @proxy_result = @object.send(@method, *@args, &@block) unless defined?(@proxy_result) @proxy_result end |