Skip to content

Instantly share code, notes, and snippets.

@owainlewis owainlewis/query.rb
Created Apr 26, 2012

Embed
What would you like to do?
Ruby HTTP DSL
# A Micro DSL for NET/HTTP
require 'net/http'
require 'net/https'
require "uri"
# Base class for making HTTP connections
module Query
# A base class for making low level HTTP requests
class Base
attr_accessor :uri, :scheme, :host, :port, :request_url, :path, :query
def initialize uri, *args, &block
@uri = URI.parse(uri)
@conn = Net::HTTP.new(@uri.host, @uri.port)
@scheme = @uri.scheme # => "http"
@host = @uri.host # => "foo.com"
@port = @uri.port # => 80
@request_url = @uri.request_uri # => "/this/is/everything?query=params"
@path = @uri.path # => "/this/is/everything"
@query = @uri.query # => "query=params"
end
def base_request
@conn.request(Net::HTTP::Get.new(@uri.request_uri))
end
# Returns the HTTP status of the initialized uri
def status
base_request.code
end
# Returns the HTTP body
def body
base_request.body
end
# Returns a hash of headers
def headers
results = {}
base_request.each_header do |k,v|
results.merge!(k => v)
end
end
# Get a single header
def header param
headers[param.downcase]
end
# Perform a HTTP GET request
def GET
http = Net::HTTP.new(@uri.host, @uri.port)
response = http.request(Net::HTTP::Get.new(@uri.request_uri))
response.to_s
end
# Perform a HTTP PUT request
def PUT; end
# Perform a HTTP DELETE request
def DELETE; end
# Method aliases for a nicer API
alias_method :get, :GET
alias_method :put, :PUT
alias_method :delete, :DELETE
end
end
http = Query::Base.new("http://google.com/")
# Sample Use
puts http.status
puts http.body
puts http.get
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.