Created
January 13, 2016 18:25
-
-
Save viktornonov/487e0d56ea6ad8873f54 to your computer and use it in GitHub Desktop.
twilio-ruby gem monkey patch for working with Typhoeus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Twilio | |
module REST | |
class Client | |
def post(path, *args) | |
params = twilify args[0]; params = {} if params.empty? | |
unless args[1] # build the full path unless already given | |
path = "#{path}.json" | |
end | |
headers = HTTP_HEADERS | |
basic_auth = 'Basic ' + ["#{@account_sid}:#{@auth_token}"].pack('m').delete("\r\n") | |
headers.merge!('Authorization' => basic_auth ) | |
#post specific headers and body | |
headers.merge!('Content-Type' => 'application/x-www-form-urlencoded') | |
query = URI.encode_www_form(params) | |
body = query | |
headers.merge!('Accept-Encoding'=>"gzip;q=1.0,deflate;q=0.6,identity;q=0.3") | |
url = "https://#{@config[:host]}#{path}" | |
#timeout headers | |
headers.merge!(open_timeout: @config[:timeout]) | |
headers.merge!(timeout: @config[:timeout]) | |
headers.merge!(verbose: true) | |
request = Typhoeus::Request.new(url, method: :post, | |
headers: headers, | |
body: body) | |
connect_and_send_typhoeus request | |
end | |
def connect_and_send_typhoeus(request) | |
@last_request = request | |
retries_left = @config[:retry_limit] | |
begin | |
response = request.run | |
@last_response = response | |
if response.kind_of? Net::HTTPServerError | |
raise Twilio::REST::ServerError | |
end | |
rescue Exception | |
raise if request.class == Net::HTTP::Post | |
if retries_left > 0 then retries_left -= 1; retry else raise end | |
end | |
if response.body and !response.body.empty? | |
object = MultiJson.load response.body | |
end | |
if response.kind_of? Net::HTTPClientError | |
raise Twilio::REST::RequestError.new object['message'], object['code'] | |
end | |
object | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment