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) ⇒ 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

Returns:

  • (String)

    evaluated string



55
56
57
58
59
60
61
# File 'lib/node_query/helper.rb', line 55

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

.get_target_node(node, keys) ⇒ Node|

Get target node by the keys.

Parameters:

  • node (Node)

    ast node

  • keys (String|Array)

    keys of child node.

Returns:

  • (Node|)

    the target node.



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

def get_target_node(node, keys)
  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) }
  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 = NodeQuery.adapter.get_node_type(node)
  end

  return child_node unless rest_keys

  return get_target_node(child_node, rest_keys)
end

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

Recursively handle child nodes.

Parameters:

  • node (Node)

    ast node

Yields:

  • (child)

    Gives a child node.

Yield Parameters:

  • child (Node)

    child node



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/node_query/helper.rb', line 34

def handle_recursive_child(node, &block)
  NodeQuery.adapter.get_children(node).each do |child|
    if NodeQuery.adapter.is_node?(child)
      block.call(child)
      handle_recursive_child(child, &block)
    elsif child.is_a?(Array)
      child.each do |child_child|
        block.call(child_child)
        handle_recursive_child(child_child, &block)
      end
    end
  end
end

.to_string(node) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/node_query/helper.rb', line 63

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

  node.to_s
end