Class: Antlers::ForNode

Inherits:
BranchNode show all
Includes:
Props, Variables
Defined in:
lib/nodes/for_node.rb

Constant Summary collapse

DEF_KEY =
:for_def
END_KEY =
:for_end

Instance Attribute Summary

Attributes included from Props

#props

Attributes inherited from BranchNode

#children

Attributes inherited from AntlerNode

#name

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Variables

#evaluate, #fallback

Methods included from Queries

user_defined_string?, wrapped_in?

Methods inherited from AntlerNode

#==, #end_name, #eql?, #hash

Constructor Details

#initialize(name:, items:, value:, key: nil, props: [], children: []) ⇒ ForNode

Returns a new instance of ForNode.



15
16
17
18
19
20
21
# File 'lib/nodes/for_node.rb', line 15

def initialize(name:, items:, value:, key: nil, props: [], children: [])
  super(name:, props:, children:)

  @items = items
  @value = value
  @key = key
end

Class Method Details

.build(segment:) ⇒ Object



46
47
48
49
# File 'lib/nodes/for_node.rb', line 46

def build(segment:, **)
  value, key, items = segment.values_at(DEF_KEY, :key, :in)
  new(name: value, key:, value:, items:)
end

.match?(segment:) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/nodes/for_node.rb', line 42

def match?(segment:)
  segment[DEF_KEY]
end

Instance Method Details

#render(current_binding: nil, parent_binding: nil, slot_node: nil) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/nodes/for_node.rb', line 23

def render(current_binding: nil, parent_binding: nil, slot_node: nil)
  output = ''

  evaluate(name: @items, current_binding:).each do |value|
    key, value = value if @key

    # TODO: Parallelize by creating new bindings and ensuring children have any args they need via RenderEvent.
    current_binding.local_variable_set(@value, value)
    current_binding.local_variable_set(@key, key) if @key

    @children.each do |child|
      output += child.render(current_binding:, parent_binding:, slot_node:) || ''
    end
  end

  output
end