Class: Yt::Request
- Inherits:
-
Object
- Object
- Yt::Request
- Defined in:
- lib/yt/request.rb
Overview
A wrapper around Net::HTTP to send HTTP requests to any web API and return their result or raise an error if the result is unexpected. The basic way to use Request is by calling run
on an instance.
Instance Method Summary collapse
-
#as_curl ⇒ String
Returns the
cURL
version of the request, useful to re-run the request in a shell terminal. -
#initialize(options = {}) ⇒ Request
constructor
Initializes a Request object.
-
#run ⇒ Net::HTTPResponse
Sends the request and returns the response.
Constructor Details
#initialize(options = {}) ⇒ Request
Initializes a Request object.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/yt/request.rb', line 53 def initialize( = {}) @method = .fetch :method, :get @expected_response = .fetch :expected_response, Net::HTTPSuccess @response_format = .fetch :response_format, :json @host = [:host] @path = [:path] @params = .fetch :params, {} # Note: This is to be invoked by auth-only YouTube APIs. @params[:key] = [:api_key] if [:api_key] # Note: This is to be invoked by all YouTube API except Annotations, # Analyitics and Uploads camelize_keys! @params if .fetch(:camelize_params, true) @request_format = .fetch :request_format, :json @body = [:body] @headers = .fetch :headers, {} @auth = [:auth] end |
Instance Method Details
#as_curl ⇒ String
Returns the cURL
version of the request, useful to re-run the request in a shell terminal.
91 92 93 94 95 96 97 98 |
# File 'lib/yt/request.rb', line 91 def as_curl 'curl'.tap do |curl| curl << " -X #{http_request.method}" http_request.each_header{|k, v| curl << %Q{ -H "#{k}: #{v}"}} curl << %Q{ -d '#{http_request.body}'} if http_request.body curl << %Q{ "#{uri.to_s}"} end end |
#run ⇒ Net::HTTPResponse
Sends the request and returns the response. If the request fails once for a temporary server error or an expired token, tries the request again before eventually raising an error.
78 79 80 81 82 83 84 85 86 |
# File 'lib/yt/request.rb', line 78 def run if matches_expectations? response.tap{parse_response!} elsif run_again? run else raise response_error, .to_json end end |