Module: RestMan::Utils

Defined in:
lib/restman/utils.rb

Overview

Various utility methods

Class Method Summary collapse

Class Method Details

.cgi_parse_header(line) ⇒ Object

:include: _doc/lib/restman/utils/cgi_parse_header.rdoc



22
23
24
25
26
27
28
29
30
# File 'lib/restman/utils.rb', line 22

def self.cgi_parse_header(line)
  types = HTTP::Accept::MediaTypes.parse(line)

  if types.empty?
    raise HTTP::Accept::ParseError.new("Found no types in header line")
  end

  [types.first.mime_type, types.first.parameters]
end

.encode_query_string(object) ⇒ Object

:include: _doc/lib/restman/utils/encode_query_string.rdoc



33
34
35
# File 'lib/restman/utils.rb', line 33

def self.encode_query_string(object)
  flatten_params(object, true).map {|k, v| v.nil? ? k : "#{k}=#{v}" }.join('&')
end

.escape(string) ⇒ Object

:include: _doc/lib/restman/utils/escape.rdoc



74
75
76
# File 'lib/restman/utils.rb', line 74

def self.escape(string)
  URI.encode_www_form_component(string)
end

.flatten_params(object, uri_escape = false, parent_key = nil) ⇒ Object

:include: _doc/lib/restman/utils/flatten_params.rdoc



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/restman/utils.rb', line 38

def self.flatten_params(object, uri_escape=false, parent_key=nil)
  unless object.is_a?(Hash) || object.is_a?(ParamsArray) ||
         (parent_key && object.is_a?(Array))
    raise ArgumentError.new('expected Hash or ParamsArray, got: ' + object.inspect)
  end

  # transform empty collections into nil, where possible
  if object.empty? && parent_key
    return [[parent_key, nil]]
  end

  # This is essentially .map(), but we need to do += for nested containers
  object.reduce([]) { |result, item|
    if object.is_a?(Array)
      # item is already the value
      k = nil
      v = item
    else
      # item is a key, value pair
      k, v = item
      k = escape(k.to_s) if uri_escape
    end

    processed_key = parent_key ? "#{parent_key}[#{k}]" : k

    case v
    when Array, Hash, ParamsArray
      result.concat flatten_params(v, uri_escape, processed_key)
    else
      v = escape(v.to_s) if uri_escape && v
      result << [processed_key, v]
    end
  }
end

.get_encoding_from_headers(headers) ⇒ Object

:include: _doc/lib/restman/utils/get_encoding_from_headers.rdoc



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/restman/utils.rb', line 8

def self.get_encoding_from_headers(headers)
  type_header = headers[:content_type]
  return nil unless type_header

  begin
    _content_type, params = cgi_parse_header(type_header)
  rescue HTTP::Accept::ParseError
    return nil
  else
    params['charset']
  end
end