Class: Wunderbar::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/wunderbar/node.rb

Direct Known Subclasses

CommentNode, DocTypeNode, PreformattedNode, TextNode

Constant Summary collapse

VOID =
%w(
  area base br col command embed hr img input keygen
  link meta param source track wbr frame
)
ESCAPE =
{
  "'" => ''',
  '&' => '&',
  '"' => '"',
  '<' => '&lt;',
  '>' => '&gt;',
  "\u00A0" => '&#xA0;',
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, *args) ⇒ Node

Returns a new instance of Node.



19
20
21
22
23
24
25
26
27
28
# File 'lib/wunderbar/node.rb', line 19

def initialize(name, *args)
  @name = name
  @text = nil
  @attrs = {}
  @children = []
  args -= symbols = args.find_all {|arg| Symbol === arg}
  @attrs = args.pop.to_hash if args.last.respond_to? :to_hash
  @text = args.shift.to_s unless args.empty?
  symbols.each {|sym| @attrs[sym] = true}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/wunderbar/node.rb', line 30

def method_missing(*args)
  if args.length == 0
    attrs[:class] = (attrs[:class].to_s.split(' ') + [name]).join(' ')
  else
    name = args.first.to_s
    err = NameError.new "undefined local variable or method `#{name}'", name
    err.set_backtrace caller
    raise err
  end
end

Instance Attribute Details

#attrsObject

Returns the value of attribute attrs.



3
4
5
# File 'lib/wunderbar/node.rb', line 3

def attrs
  @attrs
end

#childrenObject

Returns the value of attribute children.



3
4
5
# File 'lib/wunderbar/node.rb', line 3

def children
  @children
end

#nameObject

Returns the value of attribute name.



3
4
5
# File 'lib/wunderbar/node.rb', line 3

def name
  @name
end

#nodeObject

Returns the value of attribute node.



3
4
5
# File 'lib/wunderbar/node.rb', line 3

def node
  @node
end

#parentObject

Returns the value of attribute parent.



3
4
5
# File 'lib/wunderbar/node.rb', line 3

def parent
  @parent
end

#textObject

Returns the value of attribute text.



3
4
5
# File 'lib/wunderbar/node.rb', line 3

def text
  @text
end

Class Method Details

.parse_css_selector(css) ⇒ Object

parse a subset of css_selectors



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/wunderbar/node.rb', line 199

def self.parse_css_selector(css)
  if css.include? ' '
    css.split(/\s+/).map {|token| parse_css_selector(token).first}
  else
    result = {}
    while css != ''
      if css =~/^([-\w]+)/
        result[:name] = $1
        css=css[$1.length..-1]
      elsif css =~/^#([-\w]+)/
        raise ArgumentError("duplicate id") if result[:id]
        result[:id] = $1
        css=css[$1.length+1..-1]
      elsif css =~/^\.([-\w]+)/
        result[:class] ||= []
        raise ArgumentError("duplicate class") if result[:class].include?  $1
        result[:class] << $1
        css=css[$1.length+1..-1]
      elsif css =~/^\[([-\w]+)=([-\w]+)\]/
        result[:attr] ||= {}
        raise ArgumentError("duplicate attribute") if result[:attr][$1]
        result[:attr][$1] = $2
        css=css[$1.length+$2.length+3..-1]
      elsif css =~/^\[([-\w]+)='([^']+)'\]/
        result[:attr] ||= {}
        raise ArgumentError("duplicate attribute") if result[:attr][$1]
        result[:attr][$1] = $2
        css=css[$1.length+$2.length+5..-1]
      elsif css =~/^\[([-\w]+)="([^"]+)"\]/
        result[:attr] ||= {}
        raise ArgumentError("duplicate attribute") if result[:attr][$1]
        result[:attr][$1] = $2
        css=css[$1.length+$2.length+5..-1]
      elsif css =~/^\*/
        css=css[1..-1]
      else
        raise ArgumentError("syntax error: #{css.inspect}")
      end
    end
    [result]
  end
end

Instance Method Details

#add_child(child) ⇒ Object



41
42
43
44
# File 'lib/wunderbar/node.rb', line 41

def add_child(child)
  @children << child
  child.parent = self
end

#at(css) ⇒ Object



194
195
196
# File 'lib/wunderbar/node.rb', line 194

def at(css)
  search(css).first
end

#preserve_spaces?Boolean

Returns:

  • (Boolean)


146
147
148
# File 'lib/wunderbar/node.rb', line 146

def preserve_spaces?
  false
end

#rootObject



150
151
152
153
154
155
156
# File 'lib/wunderbar/node.rb', line 150

def root
  if parent
    parent.root
  else
    self
  end
end

#search(css) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/wunderbar/node.rb', line 158

def search(css)
  css = Node.parse_css_selector(css) if String === css

  matches = []
  if children
    children.each { |child| matches += child.search(css) if Node === child }
  end

  pattern = css.first

  if pattern[:id]
    return matches unless attrs and attrs[:id] == pattern[:id]
  end

  if pattern[:class]
    names = attrs ? attrs[:class].to_s.split(' ') : []
    return matches unless pattern[:class].all? {|name| names.include? name}
  end

  if pattern[:name]
    return matches unless name == pattern[:name]
  end

  if pattern[:attr]
    return matches unless attrs and pattern[:attr].all? do |k1, v1| 
      attrs.any? {|k2, v2| k1.to_s == k2.to_s and v1.to_s == v2.to_s}
    end
  end

  if css.length == 1
    matches << self
  else
    matches += search(css[1..-1])
  end
end

#serialize(options = {}, result = [], indent = '') ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/wunderbar/node.rb', line 70

def serialize(options = {}, result = [], indent = '')
  line = "#{indent}<#{name}"

  attrs.each do |name, value| 
    next unless value
    name = name.to_s.gsub('_','-') if Symbol === name
    value=name if value==true
    line += " #{name}=\"#{value.to_s.gsub(/[&\"<>\u00A0]/,ESCAPE)}\""
  end

  if children.empty? 
    if options[:pre]
      line += ">#{options[:pre]}#{text}#{options[:post]}</#{name}>"
    else
      width = options[:width] unless preserve_spaces?

      if text
        line += ">#{text.to_s.gsub(/[&<>\u00A0]/,ESCAPE)}</#{name}>"
      elsif VOID.include? name.to_s
        line += "/>"
      else
        line += "></#{name}>"
      end

      if indent and width and (line.length > width or line.include? "\n")
        reflowed = IndentedTextNode.reflow(indent, line, width,
          options[:indent])
        line = reflowed.pop
        result.push(*reflowed)
      end
    end
  elsif CompactNode === self and not CompactNode === parent
    work = []
    walk(work, nil, options)
    width = options[:width]
    if width
      line += ">"
      work = work.join + "</#{name}>"
      if line.length + work.length <= width
        line += work
      else
        # split work into tokens with balanced <>
        tokens = work.split(' ')
        (tokens.length-1).downto(1)  do |i|
          if tokens[i].count('<') != tokens[i].count('>')
            tokens[i-1,2] = tokens[i-1] + ' ' + tokens[i]
          end
        end

        line += tokens.shift

        # add tokens to line, breaking when line length would exceed width
        tokens.each do |token|
          if line.length + token.length < width
            line += ' ' + token
          else
            result << line
            line = indent.to_s + options[:indent] + token
          end
        end
      end
    else
      line += ">#{work.join}</#{name}>"
    end
  else
    result <<  line+">#{options[:pre]}" if parent

    walk(result, indent, options) unless children.empty?

    line = "#{indent}#{options[:post]}</#{name}>"
  end

  result << line if parent
  result
end

#walk(result, indent, options) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/wunderbar/node.rb', line 46

def walk(result, indent, options)
  indent += options[:indent] if indent and parent
  first = true
  spaced = false

  if preserve_spaces?
    options = options.dup
    options[:space] = :preserve
  end

  children.each do |child| 
    next unless child
    result << '' if (spaced or SpacedNode === child) and not first
    if String === child
      child = child.gsub(/\s+/, ' ') unless options[:space] == :preserve
      result << child
    else
      child.serialize(options, result, indent)
    end
    first = false
    spaced = (SpacedNode === child)
  end
end