class Builder
A builder for constructing environments using a DSL.
Definitions
def self.for(*facets, **values, &block)
Create a new environment with facets and values.
Signature
-
parameter
facetsArray(Module) Modules to include in the environment.
-
parameter
valuesHash Key-value pairs to define as methods.
-
parameter
blockProc A block for additional configuration.
-
returns
Module The constructed environment module.
Implementation
def self.for(*facets, **values, &block)
top = ::Module.new
builder = self.new(top)
facets.each do |facet|
builder.include(facet)
end
values.each do |key, value|
if value.is_a?(::Proc)
builder.method_missing(key, &value)
else
builder.method_missing(key, value)
end
end
# This allows for a convenient syntax, e.g.:
#
# Builder.for do
# foo 42
# end
#
# or:
#
# Builder.for do |builder|
# builder.foo 42
# end
if block_given?
if block.arity == 0
builder.instance_exec(&block)
else
yield builder
end
end
return top
end
def initialize(facet = ::Module.new)
Initialize a new builder.
Signature
-
parameter
facetModule The module to build into, defaults to a new
Module.
Implementation
def initialize(facet = ::Module.new)
@facet = facet
end
def include(target)
Include a module or other includable object into the environment.
Signature
-
parameter
targetModule The module to include.
Implementation
def include(target)
if target.class == ::Module
@facet.include(target)
elsif target.respond_to?(:included)
target.included(@facet)
else
::Kernel.raise ::ArgumentError, "Cannot include #{target.inspect} into #{@facet.inspect}!"
end
end
def method_missing(name, argument = nil, &block)
Define methods dynamically on the environment.
Signature
-
parameter
nameSymbol The method name to define.
-
parameter
argumentObject The value to return from the method.
-
parameter
blockProc A block to use as the method implementation.
Implementation
def method_missing(name, argument = nil, &block)
if block
@facet.define_method(name, &block)
else
@facet.define_method(name){argument}
end
end