Class: Partigirb::Transport

Inherits:
Object show all
Defined in:
lib/partigirb/transport.rb

Constant Summary collapse

CRLF =
"\r\n"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(consumer) ⇒ Transport

Returns a new instance of Transport.



18
19
20
# File 'lib/partigirb/transport.rb', line 18

def initialize(consumer)
  @consumer = consumer
end

Instance Attribute Details

#consumerObject

Returns the value of attribute consumer.



16
17
18
# File 'lib/partigirb/transport.rb', line 16

def consumer
  @consumer
end

#debugObject

Returns the value of attribute debug.



16
17
18
# File 'lib/partigirb/transport.rb', line 16

def debug
  @debug
end

Instance Method Details

#execute_request(method, url, options = {}) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/partigirb/transport.rb', line 50

def execute_request(method,url,options={})
  http = Net::HTTP.new(url.host, url.port)
  
  req = req_class(method).new(url.request_uri)
  add_headers(req,options[:headers])
  if file_param?(options[:params])
    add_multipart_data(req,options[:params])
  else
    add_form_data(req,options[:params])
  end
  
  # Sign the request with OAuth
  # when there is no options[:access_token] the request is signed without oauth_token
  # so it will be a Partigi OAuth Readonly request
  req.oauth!(http, @consumer, options[:access_token])
  
  dump_request(req) if debug
  res = http.request(req)
  dump_response(res) if debug
  res
end

#query_string(params) ⇒ Object



72
73
74
75
76
77
78
79
80
81
# File 'lib/partigirb/transport.rb', line 72

def query_string(params)
  query = case params
    when Hash then params.map{|key,value| url_encode_param(key,value) }.join("&")
    else url_encode(params.to_s)
  end
  if !(query == nil || query.length == 0) && query[0,1] != '?'
    query = "?#{query}"
  end
  query
end

#req_class(method) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/partigirb/transport.rb', line 24

def req_class(method)
  case method
    when :get then Net::HTTP::Get
    when :post then Net::HTTP::Post
    when :put then Net::HTTP::Put
    when :delete then Net::HTTP::Delete
  end
end

#request(method, string_url, options = {}) ⇒ Object

Options are one of

  • :params - a hash of parameters to be sent with the request. If a File is a parameter value, \

    a multipart request will be sent. If a Time is included, .httpdate will be called on it.
    
  • :headers - a hash of headers to send with the request



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/partigirb/transport.rb', line 37

def request(method, string_url, options={})
  params = stringify_params(options[:params])
  if method == :get && params
    string_url << query_string(params)
  end
  url = URI.parse(string_url)
  begin
    execute_request(method,url,options)
  rescue Timeout::Error
    raise "Timeout while #{method}ing #{url.to_s}"
  end
end