Created
November 4, 2014 17:45
-
-
Save makevoid/7a24c820aa98d392c217 to your computer and use it in GitHub Desktop.
Simple wrapper around Excon with json parsing included
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
# Simple wrapper around Excon with json parsing included | |
# | |
# | |
# Make a JSON get request: | |
# | |
# JSONR.get("http://echo.jsontest.com/quill/awesome/very/bacon") | |
# # => {"quill"=>"awesome", "very"=>"bacon"} # it returns a hash | |
# | |
# | |
# Use the pipelining api: | |
# | |
# host = "http://echo.jsontest.com" | |
# j = JSONR.new host | |
# j.get # makes a get request to host | |
# j.get "/foo/bar" # => {"foo"=>"bar"} | |
# j.get "/baz/lol" # => {"baz"=>"lol"} | |
# # note: all the requests use the same connection thanks to http pipelining | |
# | |
class JSONR | |
# simple api | |
def self.get(url) | |
resp = Excon.get url | |
parse resp.body | |
end | |
def self.post(url) | |
resp = Excon.post url | |
parse resp.body | |
end | |
def self.parse(string) | |
JSON.parse string | |
end | |
# pipelining api | |
attr_reader :excon | |
def initialize(host) | |
@excon = Excon.new host | |
end | |
def get(path="/", persistent: true) | |
resp = @excon.get path: path, persistent: persistent | |
self.class.parse resp.body | |
end | |
def post(path="/", persistent: true) | |
resp = @excon.post path: path, persistent: persistent | |
self.class.parse resp.body | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment