Class: LazyMethods::Proxy

Inherits:
Object
  • Object
show all
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

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