module KOAUtils::Request
Public Class Methods
make(opts)
click to toggle source
# File lib/koa-utils/request.rb, line 35 def self.make(opts) opts[:tries] ||= 1 opts[:timeout] ||= 10 opts[:url] = build_url(opts) opts[:body] = build_body(opts) execute(opts) end
Private Class Methods
build_body(opts)
click to toggle source
# File lib/koa-utils/request.rb, line 86 def self.build_body(opts) body = "" if opts[:type] == :post || opts[:type] == :put body = ::JSON.dump(opts[:data]) if opts[:data] end body end
build_url(opts)
click to toggle source
# File lib/koa-utils/request.rb, line 94 def self.build_url(opts) url = opts[:url] if opts[:type] == :get || opts[:type] == :delete url += "?"+hash_to_query(opts[:data]) if opts[:data] end url end
execute(opts)
click to toggle source
# File lib/koa-utils/request.rb, line 47 def self.execute(opts) opts[:tries].times do begin ::Timeout::timeout(opts[:timeout]) do return ResponseDecorator.new(net_request(opts)) end rescue ::Timeout::Error end end KOAUtils::TimeoutResponse.new end
hash_to_query(hash)
click to toggle source
# File lib/koa-utils/request.rb, line 102 def self.hash_to_query(hash) hash.map{|k,v| "#{CGI.escape(k.to_s)}=#{CGI.escape(v.to_s)}"}.join("&") end
net_request(opts)
click to toggle source
# File lib/koa-utils/request.rb, line 61 def self.net_request(opts) uri = ::URI.parse(opts[:url]) http = ::Net::HTTP.new(uri.host, uri.port) http.use_ssl = uri.scheme == "https" request = request_factory(opts[:type]).new(uri.request_uri) request.basic_auth uri.user, uri.password if uri.user request.basic_auth opts[:auth][:user], opts[:auth][:pass] if opts[:auth] if opts[:type] == :post || opts[:type] == :put request.add_field('Content-Type', 'application/json') request.add_field('Content-Length', opts[:body].size) request.body = opts[:body] end http.request(request) end
request_factory(type)
click to toggle source
# File lib/koa-utils/request.rb, line 79 def self.request_factory(type) return ::Net::HTTP::Post if type == :post return ::Net::HTTP::Put if type == :put return ::Net::HTTP::Delete if type == :delete return ::Net::HTTP::Get if type == :get end