Class: Cardiac::ExtensionBuilder

Inherits:
Proxy
  • Object
show all
Defined in:
lib/cardiac/util.rb

Overview

A specialized proxy class for building extension modules while supporting method_missing.

Direct Known Subclasses

DeclarationBuilder

Instance Method Summary collapse

Methods inherited from Proxy

#respond_to?

Constructor Details

#initialize(builder, extension_module = nil) ⇒ ExtensionBuilder

Returns a new instance of ExtensionBuilder.



50
51
52
53
# File 'lib/cardiac/util.rb', line 50

def initialize(builder,extension_module=nil)
  @builder = builder
  @extension_module = extension_module
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

Delegates to the builder, saves it’s return value as the new builder, and returns self.



111
112
113
114
115
116
117
118
# File 'lib/cardiac/util.rb', line 111

def method_missing(name, *args, &block)
  if @builder.respond_to?(name)
    @builder = @builder.__send__(name, *args, &block)
    self
  else
    super
  end
end

Instance Method Details

#__extension_module__Object

Lazily creates the extension module.



75
76
77
# File 'lib/cardiac/util.rb', line 75

def __extension_module__
  @extension_module ||= ::Module.new
end

#extension_eval(&block) ⇒ Object

Performs a :module_eval on the extension module, temporarily defining :method_missing on it’s singleton class for the duration of the block.



57
58
59
# File 'lib/cardiac/util.rb', line 57

def extension_eval(&block)
  extension_exec(&block)
end

#extension_exec(*args, &block) ⇒ Object

Performs a :module_eval or :module_exec on the extension module, temporarily defining :method_missing on it’s singleton class for the duration of the block.



63
64
65
66
67
68
69
70
71
72
# File 'lib/cardiac/util.rb', line 63

def extension_exec(*args, &block)
  orig_missing = build_method_missing
  begin
    args.empty? ? __extension_module__.module_eval(&block) : __extension_module__.module_exec(*args,&block)
  ensure
    __extension_module__.singleton_class.send(:remove_method, :method_missing)
    __extension_module__.define_singleton_method :method_missing, orig_missing if orig_missing
  end
  @builder
end