Class: Plist::StreamParser

Inherits:
Object
  • Object
show all
Defined in:
lib/plist/parser.rb

Constant Summary collapse

TEXT =
/([^<]+)/
CDATA =
/<!\[CDATA\[(.*?)\]\]>/
XMLDECL_PATTERN =
/<\?xml\s+(.*?)\?>*/m
DOCTYPE_PATTERN =
/\s*<!DOCTYPE\s+(.*?)(\[|>)/m
COMMENT_START =
/\A<!--/
COMMENT_END =
/.*?-->/m
UNIMPLEMENTED_ERROR =
'Unimplemented element. ' \
'Consider reporting via https://github.com/patsplat/plist/issues'

Instance Method Summary collapse

Constructor Details

#initialize(plist_data_or_file, listener) ⇒ StreamParser

Returns a new instance of StreamParser.



75
76
77
78
79
80
81
82
83
84
85
# File 'lib/plist/parser.rb', line 75

def initialize(plist_data_or_file, listener)
  if plist_data_or_file.respond_to? :read
    @xml = plist_data_or_file.read
  elsif File.exist? plist_data_or_file
    @xml = File.read(plist_data_or_file)
  else
    @xml = plist_data_or_file
  end

  @listener = listener
end

Instance Method Details

#parseObject



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
# File 'lib/plist/parser.rb', line 96

def parse
  plist_tags = PTag.mappings.keys.join('|')
  start_tag  = /<(#{plist_tags})([^>]*)>/i
  end_tag    = /<\/(#{plist_tags})[^>]*>/i

  require 'strscan'

  @scanner = StringScanner.new(@xml)
  until @scanner.eos?
    if @scanner.scan(COMMENT_START)
      @scanner.scan(COMMENT_END)
    elsif @scanner.scan(XMLDECL_PATTERN)
      encoding = parse_encoding_from_xml_declaration(@scanner[1])
      next if encoding.nil?

      # use the specified encoding for the rest of the file
      next unless String.method_defined?(:force_encoding)
      @scanner.string = @scanner.rest.force_encoding(encoding)
    elsif @scanner.scan(DOCTYPE_PATTERN)
      next
    elsif @scanner.scan(start_tag)
      @listener.tag_start(@scanner[1], nil)
      if (@scanner[2] =~ /\/$/)
        @listener.tag_end(@scanner[1])
      end
    elsif @scanner.scan(TEXT)
      @listener.text(@scanner[1])
    elsif @scanner.scan(CDATA)
      @listener.text(@scanner[1])
    elsif @scanner.scan(end_tag)
      @listener.tag_end(@scanner[1])
    else
      raise UnimplementedElementError.new(UNIMPLEMENTED_ERROR)
    end
  end
end