Class: Factrey::Blueprint

Inherits:
Object
  • Object
show all
Defined in:
lib/factrey/blueprint.rb,
lib/factrey/blueprint/node.rb,
lib/factrey/blueprint/type.rb,
lib/factrey/blueprint/instantiator.rb

Overview

Represents how to create a set of objects. Blueprint can be created and extended by the Blueprint DSL. See blueprint.

Defined Under Namespace

Classes: Instantiator, Node, Type

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBlueprint

Creates an empty blueprint.



17
18
19
# File 'lib/factrey/blueprint.rb', line 17

def initialize
  @nodes = {}
end

Instance Attribute Details

#nodesHash{Symbol => Node} (readonly)

Returns a set of nodes.

Returns:

  • (Hash{Symbol => Node})

    a set of nodes



12
13
14
# File 'lib/factrey/blueprint.rb', line 12

def nodes
  @nodes
end

#resultObject (readonly)

Returns the result of the DSL code is defined here.

Returns:

  • (Object)

    the result of the DSL code is defined here



14
15
16
# File 'lib/factrey/blueprint.rb', line 14

def result
  @result
end

Instance Method Details

#add_nodeNode

Add a node. This method is used by DSL and usually does not need to be called directly.

Returns:

Raises:

  • (ArgumentError)


41
42
43
44
45
46
47
# File 'lib/factrey/blueprint.rb', line 41

def add_node(...)
  node = Node.new(...)
  raise ArgumentError, "duplicate node: #{node.name}" if nodes.member?(node.name)

  nodes[node.name] = node
  node
end

#define_result(result, overwrite: false) ⇒ Object

Define the result. This method is used by DSL and usually does not need to be called directly.

Parameters:

  • result (Object)
  • overwrite (Boolean) (defaults to: false)

    whether to overwrite the existing result



52
53
54
55
56
# File 'lib/factrey/blueprint.rb', line 52

def define_result(result, overwrite: false)
  return if defined?(@result) && !overwrite

  @result = result
end

#dupBlueprint

Returns:



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/factrey/blueprint.rb', line 22

def dup
  result = self.class.new

  nodes.each_value do |node|
    result.add_node(
      node.name,
      node.type,
      # This is OK since Hash insertion order in Ruby is retained
      ancestors: node.ancestors.map { result.nodes[_1.name] },
      args: node.args.dup,
      kwargs: node.kwargs.dup,
    )
  end

  result
end

#instantiate(context = nil) ⇒ (Object, {Symbol => Object})

Create a set of objects and compute the result based on this blueprint.

Parameters:

  • context (Object) (defaults to: nil)

    context object to be passed to the factories

Returns:

  • ((Object, {Symbol => Object}))

    the result and the created objects



61
62
63
64
65
66
# File 'lib/factrey/blueprint.rb', line 61

def instantiate(context = nil)
  instantiator = Instantiator.new(context, self)
  objects = instantiator.instantiate_objects
  result = instantiator.instantiate_result
  [result, objects]
end