Class: ParserGirl::Parser

Inherits:
Object
  • Object
show all
Includes:
Attributes
Defined in:
lib/parser_girl/parser.rb

Instance Method Summary collapse

Methods included from Attributes

#[], #to_h

Constructor Details

#initialize(xml = nil, attrs = nil) ⇒ Parser

Returns a new instance of Parser.



5
6
7
8
9
# File 'lib/parser_girl/parser.rb', line 5

def initialize(xml=nil, attrs=nil)
  @xml = xml
  @attrs = attrs
  @stack = nil
end

Instance Method Details

#contentObject



11
12
13
# File 'lib/parser_girl/parser.rb', line 11

def content
  return @xml.dup
end

#find(needle) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/parser_girl/parser.rb', line 15

def find(needle)
  haystack_base = @xml

  haystack = haystack_base
  pos = 0
  result = []
  @stack = []
  while true do
    break unless haystack =~ /\<([^!][^\>]*)\>/i

    content = $1 # tag-hit
    b = $`.length + 1 # relative beginning in haystack
    e = content.length + b + 1 # relative ending in haystack

    if content =~ /^([^\s]+)/ && $1.downcase == "script" &&
      haystack =~ /\<\/script(\s[^\>]*)?\>/i

      e = $`.length + $&.length
    end

    if content =~ /^#{needle}(\s.*)?$/i
      @stack << { :position => pos+e, :attrs => split_attr($1) }
    elsif content =~ /^\/#{needle}(\s.*)?$/i
      hash = pop(haystack_base, b+pos-1)
      result << Parser.new(hash[:content], hash[:attrs]) if hash
    end
    pos += e
    haystack = haystack_base[pos, haystack_base.length-pos]
  end
  # pop rest and append
  result += @stack.map{ |hash| Parser.new("", hash[:attrs]) }
  return Proxy.new(result)
end