Sha256: 4eaf0b92a4419a52420dbc20b64a2ba5412573a9959ad607af490af7af6be928

Contents?: true

Size: 1.22 KB

Versions: 1

Compression:

Stored size: 1.22 KB

Contents

module AmazonProduct
  module Builder
    # Builds a hash from a Nokogiri XML document.
    #
    # In earlier versions of Sucker, I was relying on the XML Mini
    # Nokogiri module in Active Support. This method essentially
    # accomplishes the same.
    #
    # Based on https://gist.github.com/335286
    def self.from_xml(xml)
      case xml
      when Nokogiri::XML::Document
        from_xml(xml.root)
      when Nokogiri::XML::Element
        result_hash = {}

        xml.attributes.each_pair do |key, attribute|
          result_hash[key] = attribute.value
        end

        xml.children.each do |child|
          result = from_xml(child)

          if child.name == 'text'
            if result_hash.empty?
              return result
            else
              result_hash['__content__'] = result
            end
          elsif result_hash[child.name]
            if result_hash[child.name].is_a? Array
              result_hash[child.name] << result
            else
              result_hash[child.name] = [result_hash[child.name]] << result
            end
          else
            result_hash[child.name] = result
          end
        end

        result_hash
      else
        xml.content.to_s
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
amazon_product-3.0.1 lib/amazon_product/builder.rb