Class: Async::Service::Environment::Builder

Inherits:
BasicObject
Defined in:
lib/async/service/environment.rb

Overview

A builder for constructing environments using a DSL.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(facet = ::Module.new) ⇒ Builder

Initialize a new builder.



60
61
62
# File 'lib/async/service/environment.rb', line 60

def initialize(facet = ::Module.new)
  @facet = facet
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, argument = nil, &block) ⇒ Object

Define methods dynamically on the environment.



80
81
82
83
84
85
86
# File 'lib/async/service/environment.rb', line 80

def method_missing(name, argument = nil, &block)
  if block
    @facet.define_method(name, &block)
  else
    @facet.define_method(name){argument}
  end
end

Class Method Details

.for(*facets, **values, &block) ⇒ Object

Create a new environment with facets and values.



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
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/async/service/environment.rb', line 19

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

Instance Method Details

#include(target) ⇒ Object

Include a module or other includable object into the environment.



66
67
68
69
70
71
72
73
74
# File 'lib/async/service/environment.rb', line 66

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