Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/em-http/core_ext/hash.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_array(array = []) ⇒ Object

Builds a hash from an array with keys as array indices.



44
45
46
47
48
49
50
# File 'lib/em-http/core_ext/hash.rb', line 44

def self.from_array(array = [])
  h = Hash.new
  array.size.times do |t|
    h[t] = array[t]
  end
  h
end

Instance Method Details

#to_paramsObject

Stolen partially from Merb : noobkit.com/show/ruby/gems/development/merb/hash/to_params.html Convert this hash to a query string:

{ :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-1111222-222-2222&address[street]=111 Ruby Ave."


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/em-http/core_ext/hash.rb', line 14

def to_params
  params = ''
  stack = []
  
  each do |k, v|
    if v.is_a?(Hash)
      stack << [k,v]
    elsif v.is_a?(Array)
      stack << [k,Hash.from_array(v)]
    else
      params << "#{k}=#{v}&"
    end
  end
  
  stack.each do |parent, hash|
    hash.each do |k, v|
      if v.is_a?(Hash)
        stack << ["#{parent}[#{k}]", v]
      else
        params << "#{parent}[#{k}]=#{v}&"
      end
    end
  end
  
  params.chop! # trailing &
  params
end