Skip to content

Instantly share code, notes, and snippets.

@mrtazz
Created December 12, 2010 15:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrtazz/738128 to your computer and use it in GitHub Desktop.
Save mrtazz/738128 to your computer and use it in GitHub Desktop.
simple couchdb API wrapper in ruby from the CouchDB wiki, with some adaptions for basic auth
require 'net/http'
module CouchDB
class Server
def initialize(host, port, options = nil)
@host = host
@port = port
@options = options
end
def delete(uri)
req = Net::HTTP::Delete.new(uri)
request(req)
end
def get(uri)
req = Net::HTTP::Get.new(uri)
request(req)
end
def put(uri, json)
req = Net::HTTP::Put.new(uri)
req["content-type"] = "application/json"
req.body = json
request(req)
end
def post(uri, json)
req = Net::HTTP::Post.new(uri)
req["content-type"] = "application/json"
req.body = json
request(req)
end
def request(req)
if !@options.nil? and @options[:user] and @options[:password]
req.basic_auth @options[:user], @options[:password]
end
res = Net::HTTP.start(@host, @port) { |http|http.request(req) }
unless res.kind_of?(Net::HTTPSuccess)
handle_error(req, res)
end
res
end
private
def handle_error(req, res)
e = RuntimeError.new("#{res.code}:#{res.message}\nMETHOD:#{req.method}\nURI:#{req.path}\n#{res.body}")
raise e
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment