Class: Taurus::XML::SAX::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/taurus/xml/sax/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(handler = Taurus::XML::SAX::Document.new, encoding = nil) ⇒ Parser

Returns a new instance of Parser.



11
12
13
14
# File 'lib/taurus/xml/sax/parser.rb', line 11

def initialize(handler = Taurus::XML::SAX::Document.new, encoding = nil)
  @document = handler
  @encoding = encoding
end

Instance Attribute Details

#documentObject

Returns the value of attribute document.



9
10
11
# File 'lib/taurus/xml/sax/parser.rb', line 9

def document
  @document
end

#encodingObject

Returns the value of attribute encoding.



9
10
11
# File 'lib/taurus/xml/sax/parser.rb', line 9

def encoding
  @encoding
end

Instance Method Details

#parse(input) ⇒ Object

Parse a string, IO, or file path. Dispatches to parse_memory / parse_io / parse_file based on the argument type.



18
19
20
21
22
23
24
25
# File 'lib/taurus/xml/sax/parser.rb', line 18

def parse(input)
  case input
  when String                then parse_memory(input)
  when ->(x) { x.respond_to?(:read) } then parse_io(input)
  else
    raise ArgumentError, "SAX parser expects a String or IO, got #{input.class}"
  end
end

#parse_file(path) ⇒ Object



65
66
67
# File 'lib/taurus/xml/sax/parser.rb', line 65

def parse_file(path)
  File.open(path, "r") { |f| parse_io(f) }
end

#parse_io(io) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/taurus/xml/sax/parser.rb', line 39

def parse_io(io)
  handler_struct = build_handler_struct
  parser_ptr = Taurus::XML::FFI.taurus_sax_parser_create(
    handler_struct.pointer, nil)
  if parser_ptr.null?
    raise Taurus::XML::Error, "taurus_sax_parser_create failed"
  end
  begin
    while (chunk = io.read(CHUNK_SIZE))
      rc = Taurus::XML::FFI.taurus_sax_parser_feed(
        parser_ptr, chunk, chunk.bytesize, 0)
      if rc != 0
        raise Taurus::XML::ParseError, "taurus_sax_parser_feed failed (rc=#{rc})"
      end
    end
    # Final flush
    rc = Taurus::XML::FFI.taurus_sax_parser_feed(parser_ptr, "", 0, 1)
    if rc != 0
      raise Taurus::XML::ParseError, "taurus_sax_parser_feed (final) failed (rc=#{rc})"
    end
  ensure
    Taurus::XML::FFI.taurus_sax_parser_free(parser_ptr)
  end
  self
end

#parse_memory(string) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/taurus/xml/sax/parser.rb', line 27

def parse_memory(string)
  string = string.dup.force_encoding("UTF-8")
  handler_struct = build_handler_struct
  rc = Taurus::XML::FFI.taurus_sax_parse(
    string, string.bytesize, handler_struct.pointer, nil)
  if rc != 0
    raise Taurus::XML::ParseError,
      "taurus_sax_parse failed (rc=#{rc})"
  end
  self
end