Sha256: 5963534bdec0fc865413d7554878ed26e53f13ac6f6babb63c83078629a4395b

Contents?: true

Size: 1.33 KB

Versions: 1

Compression:

Stored size: 1.33 KB

Contents

require 'active_support/core_ext/hash/conversions'

module Zuora
  class Response
    attr_reader :raw

    # @param [Faraday::Response]
    # @return [Zuora::Response]
    def initialize(response)
      @raw = response
    end

    # Convert XML body to object-like nested hash.
    # @return [Hashie::Mash] object-like nested hash
    def to_h
      doc = Nokogiri::XML raw.body
      hash = Hash.from_xml doc.to_xml
      Hashie::Mash.new(symbolize_keys_deep(hash))
    end

    private

    # Given a key, convert to symbol, removing XML namespace, if any.
    # @param [String] key - a key, either "abc" or "abc:def"
    # @return [Symbol]
    def symbolize_key(key)
      return key unless key.respond_to?(:split)
      key.split(':').last.underscore.to_sym
    end

    # Recursively transforms a hash
    # @param [Hash] hash
    # @return [Hash]
    def symbolize_keys_deep(hash)
      return hash unless hash.is_a?(Hash)

      Hash[hash.map do |key, value|
        # if value is array, loop each element and recursively symbolize keys
        if value.is_a? Array
          value = value.map { |element| symbolize_keys_deep(element) }
          # if value is hash, recursively symbolize keys
        elsif value.is_a? Hash
          value = symbolize_keys_deep(value)
        end

        [symbolize_key(key), value]
      end]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
zuora-ruby-0.3.0 lib/zuora/response.rb