Class: BetterHtml::AST::Iterator

Inherits:
Object
  • Object
show all
Defined in:
lib/better_html/ast/iterator.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(types, &block) ⇒ Iterator

Returns a new instance of Iterator.



7
8
9
10
# File 'lib/better_html/ast/iterator.rb', line 7

def initialize(types, &block)
  @types = types.nil? ? nil : Array.wrap(types)
  @block = block
end

Class Method Details

.descendants(root_node, type) ⇒ Object



24
25
26
27
28
29
# File 'lib/better_html/ast/iterator.rb', line 24

def self.descendants(root_node, type)
  Enumerator.new do |yielder|
    t = new(type) { |node| yielder << node }
    t.traverse(root_node)
  end
end

Instance Method Details

#traverse(node) ⇒ Object



12
13
14
15
16
# File 'lib/better_html/ast/iterator.rb', line 12

def traverse(node)
  return unless node.is_a?(::AST::Node)
  @block.call(node) if @types.nil? || @types.include?(node.type)
  traverse_all(node)
end

#traverse_all(nodes) ⇒ Object



18
19
20
21
22
# File 'lib/better_html/ast/iterator.rb', line 18

def traverse_all(nodes)
  nodes.to_a.each do |node|
    traverse(node) if node.is_a?(::AST::Node)
  end
end