Sha256: 2b405f9b497195274dd6f7a7af2bb39385d7e7914c7ca490149f8190e1d86f07

Contents?: true

Size: 1.93 KB

Versions: 9

Compression:

Stored size: 1.93 KB

Contents

#
# Typhoeus encodes arrays as hashes {'0' => v0, '1' => v1, .., 'n' => vN }
#
# To fix this in your rails server your should:
# in Gemfile:
#     gem 'logical_model', '~> 0.3.2'
#
# in application_controller.rb:
#
#    require 'typhoeus_fix/array_decoder'
#    class ApplicationController < ActionController::Base
#      include TyphoeusFix
#      before_filter :decode_typhoeus_arrays
#    end
#
module TyphoeusFix
  # Recursively decodes Typhoeus encoded arrays in given Hash.
  #
  # @example Use directly in a Rails controller.
  #    class ApplicationController
  #       before_filter :decode_typhoeus_arrays
  #    end
  #
  # @author Dwayne Macgowan
  #
  def decode_typhoeus_arrays
    decode!(params)
  end

  # Recursively decodes Typhoeus encoded arrays in given Hash.
  #
  # @param hash [Hash]. This Hash will be modified!
  #
  # @return [Hash] Hash with properly decoded nested arrays.
  def decode!(hash)
    return hash unless hash.is_a?(Hash)
    hash.each_pair do |key,value|
      if value.is_a?(Hash)
        decode!(value)
        hash[key] = convert(value)
      end
    end
    hash
  end

  def decode(hash)
    decode!(hash.dup)
  end

  private

  # Checks if Hash is an Array encoded as a Hash.
  # Specifically will check for the Hash to have this
  # form: {'0' => v0, '1' => v1, .., 'n' => vN }
  #
  # @param hash [Hash]
  #
  # @return [Boolean] True if its a encoded Array, else false.
  def encoded?(hash)
    return false if hash.empty?
    if hash.keys.size > 1
      keys = hash.keys.map{|i| i.to_i if i.respond_to?(:to_i)}.sort
      keys == hash.keys.size.times.to_a
    else
      hash.keys.first =~ /0/
    end
  end

  # If the Hash is an array encoded by typhoeus an array is returned
  # else the self is returned
  #
  # @param hash [Hash] The Hash to convert into an Array.
  #
  # @return [Arraya/Hash]
  def convert(hash)
    if encoded?(hash)
      Hash[hash.sort_by{|k,v|k.to_i}].values
    else
      hash
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
logical_model-0.7.3 lib/typhoeus_fix/array_decoder.rb
logical_model-0.7.2 lib/typhoeus_fix/array_decoder.rb
logical_model-0.7.1 lib/typhoeus_fix/array_decoder.rb
logical_model-0.7.0 lib/typhoeus_fix/array_decoder.rb
logical_model-0.6.6 lib/typhoeus_fix/array_decoder.rb
logical_model-0.6.5 lib/typhoeus_fix/array_decoder.rb
logical_model-0.6.4 lib/typhoeus_fix/array_decoder.rb
logical_model-0.6.3 lib/typhoeus_fix/array_decoder.rb
logical_model-0.6.2 lib/typhoeus_fix/array_decoder.rb