Skip to content

Instantly share code, notes, and snippets.

@leejarvis
Created January 3, 2013 12:12
Show Gist options
  • Save leejarvis/4443038 to your computer and use it in GitHub Desktop.
Save leejarvis/4443038 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'net/http'
require 'json'
module ResponseMethods
def json_body
JSON.parse(self.body)
end
end
class Requests
def self.request(method, url)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
klass = Net::HTTP.const_get(method)
request = klass.new(uri.request_uri)
yield request if block_given?
response = http.request(request)
response.extend ResponseMethods
response
end
def self.get(url)
request(:Get, url)
end
def self.post(url, params = {})
request(:Post, url) do |req|
req.set_form_data(params)
end
end
end
response = Requests.get('http://jsonip.com/')
p response.json_body['ip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment