module Flexparser # # Wraps Nokogiri::Xml::Document to automatically hand down namespaces # to fragments generated by #xpath # class Fragment extend Forwardable attr_reader :doc attr_writer :namespaces def_delegators(:@doc, :text, :empty?, :map, :each, :namespaces, :collect_namespaces) def initialize(str, namespaces: {}) @doc = str.is_a?(String) ? Nokogiri::XML(str) : str @propagated_namespaces = namespaces end def to_s "#{self.class}: \n\tNamespaces: #{_namespaces} \tRaw:\n\t\t#{@raw_doc}\tNokogiri:\n#{doc}" end # # The same as Nokogiri::Xml::Document#xpath but # namespaces are passed down to resulting fragments. # def xpath(path) FragmentBuilder .build(doc.xpath(path, propagating_namespaces)) end def propagating_namespaces return @propagated_namespaces unless doc.respond_to?(:namespaces) if doc.respond_to?(:collect_namespaces) return @propagated_namespaces.merge doc.collect_namespaces end @propagated_namespaces.merge doc.namespaces end alias pns propagating_namespaces end end