Class: NodeQuery::Helper

Inherits:
Object
  • Object
show all
Defined in:
lib/node_query/helper.rb

Class Method Summary collapse

Class Method Details

.evaluate_node_value(node, str, adapter) ⇒ String

Evaluate node value.

Examples:

source code of the node is @id = id
evaluated_node_value(node, "@{{value}}") # => @id

Parameters:

  • node (Node)

    ast node

  • str (String)

    string to be evaluated

  • adapter (NodeQuery::Adapter)

    adapter

Returns:

  • (String)

    evaluated string



50
51
52
53
54
55
56
# File 'lib/node_query/helper.rb', line 50

def evaluate_node_value(node, str, adapter)
  str.scan(/{{(.+?)}}/).each do |match_data|
    target_node = NodeQuery::Helper.get_target_node(node, match_data.first, adapter)
    str = str.sub("{{#{match_data.first}}}", to_string(target_node, adapter))
  end
  str
end

.get_target_node(node, keys, adapter) ⇒ Node|

Get target node by the keys.

Parameters:

  • node (Node)

    ast node

  • keys (String|Array)

    keys of child node.

  • adapter (NodeQuery::Adapter)

Returns:

  • (Node|)

    the target node.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/node_query/helper.rb', line 10

def get_target_node(node, keys, adapter)
  return unless node

  first_key, rest_keys = keys.to_s.split('.', 2)
  if node.is_a?(Array) && first_key === "*"
    return node.map { |child_node| get_target_node(child_node, rest_keys, adapter) }
  end

  if node.is_a?(Array) && first_key =~ /\d+/
    child_node = node[first_key.to_i]
  elsif node.respond_to?(first_key)
    child_node = node.send(first_key)
  elsif first_key == "node_type"
    child_node = adapter.get_node_type(node)
  end

  return child_node unless rest_keys

  return get_target_node(child_node, rest_keys, adapter)
end

.handle_recursive_child(node, adapter) {|child| ... } ⇒ Object

Recursively handle child nodes.

Parameters:

Yields:

  • (child)

    Gives a child node.

Yield Parameters:

  • child (Node)

    child node



36
37
38
39
40
# File 'lib/node_query/helper.rb', line 36

def handle_recursive_child(node, adapter, &block)
  adapter.get_children(node).each do |child|
    handle_child(child, adapter, &block)
  end
end

.to_string(node, adapter) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/node_query/helper.rb', line 58

def to_string(node, adapter)
  if adapter.is_node?(node)
    return adapter.get_source(node)
  end

  node.to_s
end