Class: Hexp::Node::Selector

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/hexp/node/selector.rb

Overview

Select nodes from a Hexp tree

This is what is backing the #select method. It serves a double purpose. At it's core it's an Enumerable for iterating over nodes that match a criterium.

It also integrates with Rewriter for selective rewriting of a Hexp tree.

Examples:

# Loop over the nodes with class="big"
hexp.select {|el| el.class? 'big' }.each { ... }
# stick all links inside a <span class="link> ... </span>
hexp.select {|el| el.tag == 'a' }.wrap(:span, class: 'link')

Direct Known Subclasses

CssSelection

Instance Method Summary (collapse)

Constructor Details

- (Selector) initialize(node, block)

A new instance of Selector



23
24
25
# File 'lib/hexp/node/selector.rb', line 23

def initialize(node, block)
  @node, @select_block = node, block
end

Instance Method Details

- (Object) attr(name, value)



37
38
39
40
41
# File 'lib/hexp/node/selector.rb', line 37

def attr(name, value)
  rewrite do |node|
    node.attr(name, value)
  end
end

- (Object) each {|@node| ... }

Yields:

  • (@node)


49
50
51
52
53
54
55
56
# File 'lib/hexp/node/selector.rb', line 49

def each(&block)
  return to_enum(:each) unless block_given?

  @node.children.each do |child|
    child.select(&@select_block).each(&block)
  end
  yield @node if @select_block.(@node)
end

- (Object) rewrite(&block)



27
28
29
30
31
32
33
34
35
# File 'lib/hexp/node/selector.rb', line 27

def rewrite(&block)
  @node.rewrite do |node, parent|
    if @select_block.(node)
      block.(node, parent)
    else
      node
    end
  end
end

- (Object) wrap(tag, attributes = {})



43
44
45
46
47
# File 'lib/hexp/node/selector.rb', line 43

def wrap(tag, attributes = {})
  rewrite do |node|
    H[tag, attributes, [node]]
  end
end