Skip to content

Instantly share code, notes, and snippets.

@makevoid
Created November 4, 2014 17:45
Show Gist options
  • Save makevoid/7a24c820aa98d392c217 to your computer and use it in GitHub Desktop.
Save makevoid/7a24c820aa98d392c217 to your computer and use it in GitHub Desktop.
Simple wrapper around Excon with json parsing included
# 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