Class: Proxies::Proxy
- Inherits:
- BasicObject
- Defined in:
- lib/proxies/proxy.rb
Instance Method Summary collapse
-
#initialize(lazy_target, options = {}, &block) ⇒ Proxy
constructor
Creates a new proxy for target.
- #method_missing(name, *args, &block) ⇒ Object
- #proxy_target ⇒ Object
- #respond_to?(name, include_private = false) ⇒ Boolean
Constructor Details
#initialize(lazy_target, options = {}, &block) ⇒ Proxy
Creates a new proxy for target. You can pass a block (anonymous module) to extend the proxy object “inline”.
Options
-
:owner
- Optional owner object -
:extend
- Module or array of modules used to extend -
the newly created proxy object
Examples
Proxy.new(lambda { [1, 2, 3] }) do
def extension_method
proxy_target.length * 500
end
end
Proxy.new(lambda { my_method }, extend: MyExtension) do
def add_owner_and_target_values
proxy_target.value + proxy_owner.value
end
end
Proxy.new(lambda { my_method }, owner: self) do
def do_something
...
end
end
Proxy.new(lambda { something }, extend: [FirstExtension, SecondExtension])
46 47 48 49 50 51 52 53 54 55 |
# File 'lib/proxies/proxy.rb', line 46 def initialize(lazy_target, = {}, &block) @lazy_target = lazy_target @owner = [:owner] if .key?(:owner) extends = ::Kernel.Array([:extend]) extends << ::Module.new(&block) extends << ::Proxies::ProxyOwner if defined?(@owner) extends << ::Proxies::ProxyRespondTo extends.each { |m| m.send(:extend_object, self) } end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object
61 62 63 |
# File 'lib/proxies/proxy.rb', line 61 def method_missing(name, *args, &block) proxy_target.send(name, *args, &block) end |
Instance Method Details
#proxy_target ⇒ Object
57 58 59 |
# File 'lib/proxies/proxy.rb', line 57 def proxy_target defined?(@target) ? @target : @target = @lazy_target.call end |
#respond_to?(name, include_private = false) ⇒ Boolean
65 66 67 |
# File 'lib/proxies/proxy.rb', line 65 def respond_to?(name, include_private = false) proxy_target.respond_to?(name, include_private) end |