Module: Desmos::Utils

Defined in:
lib/desmos/utils.rb

Class Method Summary collapse

Class Method Details

.bytesize(string) ⇒ Object



53
54
55
# File 'lib/desmos/utils.rb', line 53

def bytesize(string)
  string.bytesize
end

.escape(s) ⇒ Object

Taken from Rack::Utils, 1.2.1 to remove Rack dependency.



5
6
7
8
9
# File 'lib/desmos/utils.rb', line 5

def escape(s)
  s.to_s.gsub(/([^ a-zA-Z0-9_.-]+)/u) {
    '%'+$1.unpack('H2'*bytesize($1)).join('%').upcase
  }.tr(' ', '+')
end

.traversal_to_param_string(traversal, escape = true) ⇒ Object



43
44
45
46
47
# File 'lib/desmos/utils.rb', line 43

def traversal_to_param_string(traversal, escape = true)
  traversal[:params].collect { |param|
    "#{Desmos::Utils.escape(param[0])}=#{Desmos::Utils.escape(param[1])}"
  }.join('&')
end

.traverse_params_hash(hash, result = nil, current_key = nil) ⇒ Object

Params are NOT escaped.



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
38
39
40
# File 'lib/desmos/utils.rb', line 13

def traverse_params_hash(hash, result = nil, current_key = nil)
  result ||= { :files => [], :params => [] }

  hash.keys.sort { |a, b| a.to_s <=> b.to_s }.collect do |key|
    new_key = (current_key ? "#{current_key}[#{key}]" : key).to_s
    case hash[key]
    when Hash
      traverse_params_hash(hash[key], result, new_key)
    when Array
      array_key = "#{new_key}[]"
      hash[key].each do |v|
        result[:params] << [array_key, v.to_s]
      end
    when File
      filename = File.basename(hash[key].path)
      types = MIME::Types.type_for(filename)
      result[:files] << [
        new_key,
        filename,
        types.empty? ? 'application/octet-stream' : types[0].to_s,
        File.expand_path(hash[key].path)
      ]
    else
      result[:params] << [new_key, hash[key].to_s]
    end
  end
  result
end