Class: Hexp::Node::Selection

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

Overview

Subset of 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

#initialize(node, block) ⇒ Selection

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initialize a selection with the root node, and the selection block used as the filtering criterion

Parameters:

  • node (Hexp::Node)

    The root of the tree to select in

  • block (Proc)

    A block that for a given node returns a truthy or falsey value



33
34
35
# File 'lib/hexp/node/selection.rb', line 33

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

Instance Method Details

#attr(name, value) ⇒ Hexp::Node

Set an attribute on all matching nodes

Parameters:

  • name (#to_s)

    The attribute name

  • value (#to_s)

    The attribute value

Returns:



67
68
69
70
71
# File 'lib/hexp/node/selection.rb', line 67

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

#each {|| ... } ⇒ Object

Yield each matching node

Yield Parameters:



95
96
97
98
99
100
101
102
# File 'lib/hexp/node/selection.rb', line 95

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

#rewrite {|| ... } ⇒ Hexp::Node

Replace matching nodes

Analogues to the main Hexp::Node#rewrite operation.

Yield Parameters:

Returns:



46
47
48
49
50
51
52
53
54
# File 'lib/hexp/node/selection.rb', line 46

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

#wrap(tag, attributes = {}) ⇒ Hexp::Node

Wrap each matching node in a specific node

Parameters:

  • tag (Symbol)

    The tag of the wrapping node

Returns:



84
85
86
87
88
# File 'lib/hexp/node/selection.rb', line 84

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