Sha256: 33f2cda666d352306b9ae90ce05e126ea39c30594f3cfc42d0e9a0f20de72a96

Contents?: true

Size: 1.22 KB

Versions: 1

Compression:

Stored size: 1.22 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

    #
    # The namespaces that are propagating to the child-fragment of this.
    #
    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.3 lib/flexparser/fragment.rb