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



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

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

#encode_field(k, v) ⇒ Object

Encode a field in an HTTP header



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

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

#encode_headers(head) ⇒ Object



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

def encode_headers(head)
  head.reduce('') do |result, (k, v)|
    # Munge keys from foo-bar-baz to Foo-Bar-Baz
    k = k.split('-').map(&:capitalize).join('-')
  result << encode_field(k, v)
  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.



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

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.



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

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

#encode_query(uri, query) ⇒ Object



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

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

#encode_request(method, uri, query) ⇒ Object



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

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

#escape(s) ⇒ Object

Escapes a URI.



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

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



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

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

#unescape(s) ⇒ Object

Unescapes a URI escaped string.



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

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