Created
December 12, 2010 15:58
-
-
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
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
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