Class: Leptris::XML::Pull::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/leptris/xml/pull.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(handle) ⇒ Parser

Returns a new instance of Parser.



40
41
42
43
# File 'lib/leptris/xml/pull.rb', line 40

def initialize(handle)
  raise Leptris::XML::ParseError, "leptris_pull_new failed" if handle.null?
  @handle = handle
end

Class Method Details

.parse(xml_or_io) ⇒ Object



31
32
33
34
# File 'lib/leptris/xml/pull.rb', line 31

def self.parse(xml_or_io)
  xml = xml_or_io.respond_to?(:read) ? xml_or_io.read : xml_or_io.to_s
  new(Leptris::XML::FFI.leptris_pull_new(xml, xml.bytesize))
end

.parse_file(path) ⇒ Object



36
37
38
# File 'lib/leptris/xml/pull.rb', line 36

def self.parse_file(path)
  new(Leptris::XML::FFI.leptris_pull_new_file(path))
end

Instance Method Details

#eachObject



52
53
54
55
56
57
58
59
60
61
# File 'lib/leptris/xml/pull.rb', line 52

def each
  return enum_for(:each) unless block_given?
  loop do
    event = next_event
    break if event.nil?
    yield event
    break if event.type == :end_document || event.type == :error
  end
  self
end

#freeObject

Releases the C parser. Safe to call twice.



46
47
48
49
50
# File 'lib/leptris/xml/pull.rb', line 46

def free
  return if @handle.nil?
  Leptris::XML::FFI.leptris_pull_free(@handle)
  @handle = nil
end

#next_eventObject

Advances the cursor and returns the next Event, or nil after the end of the document. Attribute values are captured during start_element because the C accessors are valid only for the most recently returned event.



75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/leptris/xml/pull.rb', line 75

def next_event
  raw = Leptris::XML::FFI.leptris_pull_next(@handle)
  return nil if raw.null?
  type = TYPES[raw.get_int(0)]
  name_ptr = raw.get_pointer(NAME_OFFSET)
  text_ptr = raw.get_pointer(TEXT_OFFSET)
  attrs = type == :start_element ? capture_attrs : nil
  Event.new(
    type: type,
    name: name_ptr.null? ? nil : name_ptr.read_string.force_encoding(Encoding::UTF_8),
    text: text_ptr.null? ? nil : text_ptr.read_string.force_encoding(Encoding::UTF_8),
    attrs: attrs
  )
end