From 1a413998a3b0ea29cd81d63afd08d9ee7f6dd5d7 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Tue, 29 Apr 2014 21:21:05 +0200 Subject: [PATCH] Track the current node in the pull parser. The current node is tracked in the instance method `node`. --- lib/oga/xml/pull_parser.rb | 16 +++++++++++----- spec/oga/xml/pull_parser/general_spec.rb | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 spec/oga/xml/pull_parser/general_spec.rb diff --git a/lib/oga/xml/pull_parser.rb b/lib/oga/xml/pull_parser.rb index 7bd55e3..c68499c 100644 --- a/lib/oga/xml/pull_parser.rb +++ b/lib/oga/xml/pull_parser.rb @@ -19,12 +19,16 @@ module Oga # This parses yields proper XML instances such as {Oga::XML::Element}. # Doctypes and XML declarations are ignored by this parser. # + # @!attribute [r] node + # The current node. + # @return [Oga::XML::Node] + # # @!attribute [r] nesting # Array containing the names of the currently nested elements. # @return [Array] # class PullParser < Parser - attr_reader :nesting + attr_reader :node, :nesting ## # @return [Array] @@ -53,6 +57,7 @@ module Oga @block = nil @nesting = [] + @node = nil end ## @@ -83,7 +88,8 @@ module Oga BLOCK_CALLBACKS.each do |method| eval <<-EOF, nil, __FILE__, __LINE__ + 1 def #{method}(*args) - @block.call(super) + @node = super + @block.call(@node) return end EOF @@ -93,11 +99,11 @@ module Oga # @see Oga::XML::Parser#on_element # def on_element(*args) - element = super + @node = super - nesting << element.name + nesting << @node.name - @block.call(element) + @block.call(@node) return end diff --git a/spec/oga/xml/pull_parser/general_spec.rb b/spec/oga/xml/pull_parser/general_spec.rb new file mode 100644 index 0000000..d28fb07 --- /dev/null +++ b/spec/oga/xml/pull_parser/general_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe Oga::XML::PullParser do + context 'tracking nodes' do + before :all do + @parser = described_class.new('') + end + + example 'track the current node' do + @parser.parse do + @parser.node.is_a?(Oga::XML::Element).should == true + end + end + + example 'reset the current node after parsing' do + @parser.parse { } + + @parser.node.nil?.should == true + end + end +end