Class: RedQuilt::NodeRef

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/red_quilt/node_ref.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(document, node_id) ⇒ NodeRef

Returns a new instance of NodeRef.



9
10
11
12
13
# File 'lib/red_quilt/node_ref.rb', line 9

def initialize(document, node_id)
  @document = document
  @arena = document.arena
  @node_id = node_id
end

Instance Attribute Details

#documentObject (readonly)

Returns the value of attribute document.



7
8
9
# File 'lib/red_quilt/node_ref.rb', line 7

def document
  @document
end

#node_idObject (readonly)

Returns the value of attribute node_id.



7
8
9
# File 'lib/red_quilt/node_ref.rb', line 7

def node_id
  @node_id
end

Instance Method Details

#childrenObject



23
24
25
# File 'lib/red_quilt/node_ref.rb', line 23

def children
  @arena.child_ids(@node_id).map { |child_id| NodeRef.new(@document, child_id) }
end

#eachObject



15
16
17
# File 'lib/red_quilt/node_ref.rb', line 15

def each(&)
  walk(&)
end

#find_all(type) ⇒ Object



53
54
55
# File 'lib/red_quilt/node_ref.rb', line 53

def find_all(type)
  walk.select { |node| node.type == type }
end

#source_locationObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/red_quilt/node_ref.rb', line 57

def source_location
  span = source_span
  return nil unless span

  start_loc = @document.source_map.line_column(span.start_byte)
  end_loc = @document.source_map.line_column(span.end_byte)

  {
    start_line: start_loc[:line],
    start_column: start_loc[:column],
    end_line: end_loc[:line],
    end_column: end_loc[:column],
  }
end

#source_spanObject



49
50
51
# File 'lib/red_quilt/node_ref.rb', line 49

def source_span
  @arena.source_span(@node_id)
end

#textObject



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/red_quilt/node_ref.rb', line 36

def text
  first_child_id = @arena.raw_first_child_id(@node_id)
  return @arena.text(@node_id) if first_child_id == -1

  text = +""
  @arena.child_ids(@node_id).each do |child_id|
    child = NodeRef.new(@document, child_id)
    fragment = child.text
    text << fragment.to_s unless fragment.nil?
  end
  text
end

#to_hObject



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/red_quilt/node_ref.rb', line 72

def to_h
  ast = {
    type: type,
    source_span: source_span,
    children: children.map(&:to_h),
  }

  attributes = ast_attributes
  ast[:attributes] = attributes unless attributes.empty?
  ast
end

#typeObject



19
20
21
# File 'lib/red_quilt/node_ref.rb', line 19

def type
  @arena.type_name(@node_id)
end

#walk {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:



27
28
29
30
31
32
33
34
# File 'lib/red_quilt/node_ref.rb', line 27

def walk(&block)
  return enum_for(:walk) unless block_given?

  yield self
  @arena.child_ids(@node_id).each do |child_id|
    NodeRef.new(@document, child_id).walk(&block)
  end
end