Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/ext/hash.rb

Constant Summary collapse

RESERVED_CHARACTERS =
/[^a-zA-Z0-9\-\.\_\~]/

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_array(array = []) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/ext/hash.rb', line 39

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

Instance Method Details

#_escape(value) ⇒ Object



4
5
6
7
8
# File 'lib/ext/hash.rb', line 4

def _escape(value)
  URI::escape(value.to_s, RESERVED_CHARACTERS)
rescue ArgumentError
  URI::escape(value.to_s.force_encoding(Encoding::UTF_8), RESERVED_CHARACTERS)
end

#to_paramsObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ext/hash.rb', line 10

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 << "#{_escape(k)}=#{_escape(v)}&"
    end
  end

  stack.each do |parent, hash|
    parent = _escape(parent) if parent.is_a? String
    hash.each do |k, v|
      if v.is_a?(Hash)
        stack << ["#{parent}[#{k}]", v]
      else
        params << "#{parent}[#{k}]=#{_escape(v)}&"
      end
    end
  end

  params.chop!
  params
end