module Nori::CoreExt::Hash

Public Instance Methods

normalize_param(key, value) click to toggle source

@param key<Object> The key for the param. @param value<Object> The value for the param.

@return <String> This key value pair as a param

@example normalize_param(:name, “Bob Jones”) #=> “name=Bob%20Jones”

# File lib/nori/core_ext/hash.rb, line 28
def normalize_param(key, value)
  if value.is_a?(Array)
    normalize_array_params(key, value)
  elsif value.is_a?(Hash)
    normalize_hash_params(key, value)
  else
    normalize_simple_type_params(key, value)
  end
end
to_params() click to toggle source

@return <String> This hash as a query string

@example

{ :name => "Bob",
  :address => {
    :street => '111 Ruby Ave.',
    :city => 'Ruby Central',
    :phones => ['111-111-1111', '222-222-2222']
  }
}.to_params
  #=> "name=Bob&address[city]=Ruby Central&address[phones][]=111-111-1111&address[phones][]=222-222-2222&address[street]=111 Ruby Ave."
# File lib/nori/core_ext/hash.rb, line 18
def to_params
  map { |k, v| normalize_param(k,v) }.flatten.join('&')
end
to_xml_attributes() click to toggle source

@return <String> The hash as attributes for an XML tag.

@example

{ :one => 1, "two"=>"TWO" }.to_xml_attributes
  #=> 'one="1" two="TWO"'
# File lib/nori/core_ext/hash.rb, line 43
def to_xml_attributes
  map do |k, v|
    %{#{k.to_s.snakecase.sub(/^(.{1,1})/) { |m| m.downcase }}="#{v}"}
  end.join(' ')
end

Private Instance Methods

encode_simple_value(value) click to toggle source
# File lib/nori/core_ext/hash.rb, line 67
def encode_simple_value(value)
  URI.encode(value.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
end
normalize_array_params(key, array) click to toggle source
# File lib/nori/core_ext/hash.rb, line 55
def normalize_array_params(key, array)
  array.map do |element|
    normalize_param("#{key}[]", element)
  end
end
normalize_hash_params(key, hash) click to toggle source
# File lib/nori/core_ext/hash.rb, line 61
def normalize_hash_params(key, hash)
  hash.map do |nested_key, element|
    normalize_param("#{key}[#{nested_key}]", element)
  end
end
normalize_simple_type_params(key, value) click to toggle source
# File lib/nori/core_ext/hash.rb, line 51
def normalize_simple_type_params(key, value)
  ["#{key}=#{encode_simple_value(value)}"]
end