Created
July 28, 2017 12:39
-
-
Save kyontan/ff28f23af2617d31b839cec2421b89b7 to your computer and use it in GitHub Desktop.
Simple rest client
This file contains hidden or 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
require 'uri' | |
require 'json' | |
require 'net/http' | |
module RestClient | |
class << self | |
def get(path) | |
execute :get, path | |
end | |
def post(path, body) | |
execute :post, path, body | |
end | |
def put(path, body) | |
execute :put, path, body | |
end | |
def delete(path) | |
execute :delete, path | |
end | |
private | |
def execute(method, path, body = nil) | |
response = request(method, path, body) | |
if method == :get && response.code.to_i == 404 | |
# retry up to 3 times | |
2.times do | |
response = request(method, path, body) | |
return if response.code.to_i == 200 | |
end | |
end | |
if response.header && response.header['Content-Type'].start_with?('application/json') | |
begin | |
JSON.parse(response.body, symbolize_names: true) | |
rescue | |
response.body | |
end | |
else | |
response.body | |
end | |
end | |
def request_class_for(method) | |
case method.downcase.to_sym | |
when :get | |
::Net::HTTP::Get | |
when :post | |
::Net::HTTP::Post | |
when :put | |
::Net::HTTP::Put | |
when :delete | |
::Net::HTTP::Delete | |
else | |
raise "method: #{method} isn't allowed." | |
end | |
end | |
def http(uri) | |
::Net::HTTP.new(uri.host, uri.port) | |
end | |
def request(method, uri, body = nil) | |
body = body.to_json if (body.is_a? Hash) || (body.is_a? Array) | |
request_path = uri.request_uri | |
# puts "#{Tty.purple}#{method.upcase} #{request_path}, #{body}#{Tty.reset}" | |
request = request_class_for(method).new(request_path.to_s) | |
request['Accept'] = 'application/json' | |
if body | |
request.content_type = 'application/json' | |
request.body = body | |
end | |
http(uri).request(request) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment