Class: KDL::Builder

Inherits:
BasicObject
Defined in:
lib/kdl/builder.rb

Defined Under Namespace

Classes: Error

Instance Method Summary collapse

Constructor Details

#initializeBuilder

Returns a new instance of Builder.



7
8
9
10
# File 'lib/kdl/builder.rb', line 7

def initialize
  @nesting = []
  @document = Document.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



64
65
66
# File 'lib/kdl/builder.rb', line 64

def method_missing(name, *args, **props, &block)
  node name, *args, **props, &block
end

Instance Method Details

#arg(value, type: nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
# File 'lib/kdl/builder.rb', line 41

def arg(value, type: nil)
  if n = current_node
    val = Value.from(value)
    val = val.as_type(type) if type
    n.arguments << val
    val
  else
    raise Error, "Can't do argument, not inside Node"
  end
end

#document(&block) ⇒ Object



12
13
14
15
# File 'lib/kdl/builder.rb', line 12

def document(&block)
  yield if block
  @document
end

#node(name = nil, *args, type: nil, **props, &block) ⇒ Object Also known as: _



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/kdl/builder.rb', line 17

def node(name = nil, *args, type: nil, **props, &block)
  n = Node.new(name&.to_s || "node", type:)
  @nesting << n
  args.each do |value|
    case value
    when ::Hash
      value.each { |k, v| prop k, v }
    else arg value
    end
  end
  props.each do |key, value|
    prop key, value
  end
  yield if block
  @nesting.pop
  if parent = current_node
    parent.children << n
  else
    @document << n
  end
  n
end

#prop(key, value, type: nil) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/kdl/builder.rb', line 52

def prop(key, value, type: nil)
  key = key.to_s
  if n = current_node
    val = Value.from(value)
    val = val.as_type(type) if type
    n.properties[key] = val
    val
  else
    raise Error, "Can't do property, not inside Node"
  end
end