Class: Goat::DOMTools::Traverser

Inherits:
Object
  • Object
show all
Includes:
Goat::DOMTools
Defined in:
lib/goat/dom.rb

Defined Under Namespace

Classes: BlockTraverser

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Goat::DOMTools

attrs, body, car_tag, dom_components, dom_node?, domid, expanded_dom, find_component, inject_prefixes, is_attrs?, nested_body?, normalized_tags, tag

Constructor Details

#initialize(tree, dlg, transpose) ⇒ Traverser

Returns a new instance of Traverser.



26
27
28
29
30
# File 'lib/goat/dom.rb', line 26

def initialize(tree, dlg, transpose)
  @tree = tree
  @dlg = dlg
  @transpose = transpose
end

Class Method Details

.transpose(tree, dlg = nil, &blk) ⇒ Object



135
136
137
# File 'lib/goat/dom.rb', line 135

def self.transpose(tree, dlg=nil, &blk)
  traverse(tree, dlg, true, &blk)
end

.traverse(tree, dlg = nil, transpose = false, &blk) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/goat/dom.rb', line 121

def self.traverse(tree, dlg=nil, transpose=false, &blk)
  d = nil

  if dlg
    d = dlg
  elsif blk
    d = BlockTraverser.new(blk, transpose)
  else
    raise "Need a delegate"
  end

  self.new(tree, d, transpose).traverse!
end

Instance Method Details

#replacement_blockObject



38
39
40
41
# File 'lib/goat/dom.rb', line 38

def replacement_block
  @rep = nil
  @replacement_block ||= lambda {|new| @rep = new}
end

#to_node(tag, attrs, body) ⇒ Object



32
33
34
35
36
# File 'lib/goat/dom.rb', line 32

def to_node(tag, attrs, body)
  tag = [tag]
  tag << attrs if attrs
  tag += normalized_tags(body)
end

#traverse(node) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/goat/dom.rb', line 43

def traverse(node)
  if node.is_a?(String)
    @dlg.string(node, &replacement_block)
    @rep || node
  elsif node == nil
    @dlg.string('', &replacement_block)
    @rep || nil
  elsif dom_node?(node)
    stay_traversing = @dlg.node(node, &replacement_block)
    rep = @rep || node

    if @transpose
      if !rep.equal?(node)
        if stay_traversing
          to_node(tag(rep), attrs(rep), traverse(body(rep)))
        else
          rep
        end
      else
        to_node(tag(node), attrs(node), traverse(body(node)))
      end
    else
      traverse(body(node))
    end
  elsif node.is_a?(Array)
    if node.size == 1
      traverse(node.first)
    else
      if @transpose
        node.map{|x| traverse(x)}
      else
        node.each{|x| traverse(x)}
      end
    end
  elsif node.kind_of?(Component)
    @dlg.component(node, &replacement_block)
    @rep || node
  else
    raise "Unknown object in the dom: #{node.inspect}"
  end
end

#traverse!Object



85
86
87
# File 'lib/goat/dom.rb', line 85

def traverse!
  traverse(@tree)
end