Sha256: 1148a47981db2832aafc003e0bb03c7c3d549dd06bd5a749b52fdf087ade6160

Contents?: true

Size: 1.14 KB

Versions: 1

Compression:

Stored size: 1.14 KB

Contents

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
flexparser-1.0.2 lib/flexparser/fragment.rb