Class: ConfigLeaf::Wrapper

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(owner, &block) ⇒ Wrapper

If passed a block, the Wrapper will #instance_eval it automatically.

Parameters:

  • owner (Object)

    Object to redirect the public methods of.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/config_leaf/wrapper.rb', line 15

def initialize(owner, &block)
  @_owner = owner

  metaclass = class << self; self; end

  (@_owner.public_methods - Object.public_instance_methods).each do |target_method|
    redirection_method = target_method.to_s.chomp('=').to_sym

    metaclass.class_eval do
      define_method redirection_method do |*args, &inner_block|
        if @_owner.respond_to? "#{redirection_method}=" and (args.any? or not @_owner.respond_to? redirection_method)
          # Has a setter and we are passing argument(s) or if we haven't got a corresponding getter.
          @_owner.send "#{redirection_method}=", *args, &inner_block
        elsif @_owner.respond_to? redirection_method
          # We have a getter or general method
          @_owner.send redirection_method, *args, &inner_block
        else
          # Should never reach here, but let's be paranoid.
          raise NoMethodError, "#{@_owner} does not have a public method, ##{redirection_method}"
        end
      end
    end
  end

  instance_eval &block if block_given?

  if instance_variables != [:@_owner]
    altered = instance_variables - [:@_owner]
    raise "Instance variable#{altered.one? ? '' : 's'} #{altered.join ", "} set in ConfigLeaf scope"
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object (private)

Raises:

  • (NoMethodError)


48
49
50
# File 'lib/config_leaf/wrapper.rb', line 48

def method_missing(meth, *args, &block)
  raise NoMethodError, "#{_owner} does not have either public method, ##{meth} or ##{meth}="
end

Instance Attribute Details

#_ownerObject (readonly)

Returns Object that the Wrapper object is redirecting to.

Returns:

  • (Object)

    Object that the Wrapper object is redirecting to.



5
6
7
# File 'lib/config_leaf/wrapper.rb', line 5

def _owner
  @_owner
end