module Recurly
  class XML
    module NokogiriAdapter
      def initialize xml
        @root = Nokogiri(xml).root
      end

      def add_element name, value = nil
        root.add_child(node = ::Nokogiri::XML::Element.new(name, root))
        node << value if value
        node
      end

      def each_element xpath = nil
        elements = xpath.nil? ? root.children : root.xpath(xpath)
        elements.each { |el| yield el }
      end

      def each element = root
        element.elements.each do |el|
          yield el
          each el, &Proc.new
        end
      end

      def name
        root.name
      end

      def [] xpath
        root.at_xpath xpath
      end

      def text xpath = nil
        if node = (xpath ? root.at_xpath(xpath) : root)
          if node.text?
            node.text
          else
            node.children.each { |e| return e.text if e.text? }
          end
        end
      end

      def text= text
        root.content = text
      end

      def to_s
        root.to_xml(:indent => 0).gsub(/$\n/, '')
      end
    end

    include NokogiriAdapter
  end
end

module Recurly
  class XML
    module NokogiriAdapter
      def initialize xml
        @root = Nokogiri(xml).root
      end

      def add_element name, value = nil
        root.add_child(node = ::Nokogiri::XML::Element.new(name, root))
        node << value if value
        node
      end

      def each_element xpath = nil
        elements = xpath.nil? ? root.children : root.xpath(xpath)
        elements.each { |el| yield el }
      end

      def each element = root
        element.elements.each do |el|
          yield el
          each el, &Proc.new
        end
      end

      def name
        root.name
      end

      def [] xpath
        root.at_xpath xpath
      end

      def text xpath = nil
        if node = (xpath ? root.at_xpath(xpath) : root)
          if node.text?
            node.text
          else
            node.children.map { |e| e.text if e.text? }.compact.join
          end
        end
      end

      def text= text
        root.content = text
      end

      def to_s
        root.to_xml(:indent => 0).gsub(/$\n/, '')
      end
    end

    include NokogiriAdapter
  end
end

Fix Nokogiri interpretation of empty nodes
Fix Nokogiri interpretation of empty nodes

Nokogiri::Element returns the number of nodes when you call
children#each, leading to text returning 0 if there are none. Instead,
let's join the texts together and return that ("" instead in that last
case).

Signed-off-by: Stephen Celis <06fa905d7f2aaced6dc72e9511c71a2a51e8aead@stephencelis.com>
