Module: Compound::Host

Defined in:
lib/compound/host.rb

Overview

Include this module in a class to gain the ability to host Parts, which each embody a module, appearing to an outside object as if the modules themselves were mixed in, while maintaining separation among the modules. Refer to the README for more information

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object

Forward an undefined method if it is in one of the Parts



26
27
28
29
30
# File 'lib/compound/host.rb', line 26

def method_missing sym, *args, &block
  component = @_compound_parts && 
              @_compound_parts.detect { |obj| obj.respond_to? sym }
  component ? (component.send sym, *args, &block) : super
end

Instance Method Details

#compound(mod) ⇒ Object

Internalize a new Part embodying the given module



11
12
13
14
15
16
17
# File 'lib/compound/host.rb', line 11

def compound mod
  @_compound_parts ||= []
  uncompound mod
  @_compound_parts.unshift ::Compound::Part.new self, mod
  mod.compounded(self) if mod.respond_to? :compounded
  return mod
end

#method(sym) ⇒ Object

Return the Method object associated with the symbol, even if it is in one of the Parts and not the Host



40
41
42
43
44
45
46
# File 'lib/compound/host.rb', line 40

def method sym
  return super if methods.include? sym
  component = @_compound_parts && 
              @_compound_parts.detect { |obj| obj.respond_to? sym }
  component ? component.method(sym) :
    raise(NameError, "undefined method `#{sym}' for object `#{self}'")
end

#respond_to?(sym) ⇒ Boolean

Pretend to also respond_to methods in the Parts as well as the Host

Returns:

  • (Boolean)


33
34
35
36
# File 'lib/compound/host.rb', line 33

def respond_to? sym
  super || !!(@_compound_parts && 
              @_compound_parts.detect { |obj| obj.respond_to? sym })
end

#uncompound(mod) ⇒ Object

Remove the Part associated with the given module



20
21
22
23
# File 'lib/compound/host.rb', line 20

def uncompound mod
  (@_compound_parts &&
  (@_compound_parts.reject! { |part| part.is_a? mod } ? mod : nil))
end