Module: Rev::HttpEncoding

Included in:
HttpClient
Defined in:
lib/rev/http_client.rb

Overview

Methods for building HTTP requests

Constant Summary collapse

HTTP_REQUEST_HEADER =
"%s %s HTTP/1.1\r\n"
FIELD_ENCODING =
"%s: %s\r\n"

Instance Method Summary collapse

Instance Method Details

#encode_cookies(cookies) ⇒ Object



108
109
110
# File 'lib/rev/http_client.rb', line 108

def encode_cookies(cookies)
  cookies.inject('') { |result, (k, v)| result << encode_field('Cookie', encode_param(k, v)) }
end

#encode_field(k, v) ⇒ Object

Encode a field in an HTTP header



96
97
98
# File 'lib/rev/http_client.rb', line 96

def encode_field(k, v)
  FIELD_ENCODING % [k, v]
end

#encode_headers(head) ⇒ Object



100
101
102
103
104
105
106
# File 'lib/rev/http_client.rb', line 100

def encode_headers(head)
  head.inject('') do |result, (key, value)|
    # Munge keys from foo-bar-baz to Foo-Bar-Baz
    key = key.split('-').map { |k| k.capitalize }.join('-')
  result << encode_field(key, value)
  end
end

#encode_hostObject

HTTP is kind of retarded that you have to specify a Host header, but if you include port 80 then further redirects will tack on the :80 which is annoying.



77
78
79
# File 'lib/rev/http_client.rb', line 77

def encode_host
  remote_host + (remote_port.to_i != 80 ? ":#{remote_port}" : "")
end

#encode_param(k, v) ⇒ Object

URL encodes a single k=v parameter.



91
92
93
# File 'lib/rev/http_client.rb', line 91

def encode_param(k, v)
  escape(k) + "=" + escape(v)
end

#encode_query(path, query) ⇒ Object



85
86
87
88
# File 'lib/rev/http_client.rb', line 85

def encode_query(path, query)
  return path unless query
  path + "?" + query.map { |k, v| encode_param(k, v) }.join('&')
end

#encode_request(method, path, query) ⇒ Object



81
82
83
# File 'lib/rev/http_client.rb', line 81

def encode_request(method, path, query)
  HTTP_REQUEST_HEADER % [method.to_s.upcase, encode_query(path, query)]
end

#escape(s) ⇒ Object

Escapes a URI.



56
57
58
59
60
# File 'lib/rev/http_client.rb', line 56

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

#munge_header_keys(head) ⇒ Object

Map all header keys to a downcased string version



70
71
72
# File 'lib/rev/http_client.rb', line 70

def munge_header_keys(head)
  head.inject({}) { |h, (k, v)| h[k.to_s.downcase] = v; h }
end

#unescape(s) ⇒ Object

Unescapes a URI escaped string.



63
64
65
66
67
# File 'lib/rev/http_client.rb', line 63

def unescape(s)
  s.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n){
    [$1.delete('%')].pack('H*')
  } 
end