2008-03-18 19:37:10 +01:00
|
|
|
require "rubygems"
|
2008-05-24 21:28:42 +02:00
|
|
|
require 'json'
|
2008-06-20 21:43:28 +02:00
|
|
|
require 'rest_client'
|
2008-06-01 19:23:24 +02:00
|
|
|
|
2008-03-18 19:37:10 +01:00
|
|
|
require File.dirname(__FILE__) + '/database'
|
|
|
|
|
|
|
|
class CouchRest
|
|
|
|
attr_accessor :uri
|
2008-06-07 17:32:51 +02:00
|
|
|
def initialize server = 'http://localhost:5984'
|
2008-03-18 19:37:10 +01:00
|
|
|
@uri = server
|
|
|
|
end
|
|
|
|
|
|
|
|
# list all databases on the server
|
|
|
|
def databases
|
|
|
|
CouchRest.get "#{@uri}/_all_dbs"
|
|
|
|
end
|
|
|
|
|
|
|
|
def database name
|
|
|
|
CouchRest::Database.new(@uri, name)
|
|
|
|
end
|
|
|
|
|
|
|
|
# get the welcome message
|
|
|
|
def info
|
|
|
|
CouchRest.get "#{@uri}/"
|
|
|
|
end
|
|
|
|
|
2008-06-15 20:43:05 +02:00
|
|
|
# restart the couchdb instance
|
|
|
|
def restart!
|
|
|
|
CouchRest.post "#{@uri}/_restart"
|
|
|
|
end
|
|
|
|
|
2008-03-18 19:37:10 +01:00
|
|
|
# create a database
|
|
|
|
def create_db name
|
|
|
|
CouchRest.put "#{@uri}/#{name}"
|
|
|
|
database name
|
|
|
|
end
|
|
|
|
|
|
|
|
class << self
|
2008-03-19 16:57:20 +01:00
|
|
|
def put uri, doc = nil
|
2008-05-24 22:17:44 +02:00
|
|
|
payload = doc.to_json if doc
|
2008-03-19 16:57:20 +01:00
|
|
|
JSON.parse(RestClient.put(uri, payload))
|
2008-03-18 19:37:10 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def get uri
|
2008-06-07 17:32:51 +02:00
|
|
|
JSON.parse(RestClient.get(uri), :max_nesting => false)
|
2008-03-19 16:57:20 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def post uri, doc = nil
|
2008-05-24 22:17:44 +02:00
|
|
|
payload = doc.to_json if doc
|
2008-03-19 16:57:20 +01:00
|
|
|
JSON.parse(RestClient.post(uri, payload))
|
2008-03-18 19:37:10 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def delete uri
|
2008-03-19 16:57:20 +01:00
|
|
|
JSON.parse(RestClient.delete(uri))
|
2008-03-18 19:37:10 +01:00
|
|
|
end
|
2008-05-23 06:57:21 +02:00
|
|
|
|
|
|
|
def paramify_url url, params = nil
|
|
|
|
if params
|
|
|
|
query = params.collect do |k,v|
|
2008-05-24 22:17:44 +02:00
|
|
|
v = v.to_json if %w{key startkey endkey}.include?(k.to_s)
|
2008-05-23 06:57:21 +02:00
|
|
|
"#{k}=#{CGI.escape(v.to_s)}"
|
|
|
|
end.join("&")
|
|
|
|
url = "#{url}?#{query}"
|
|
|
|
end
|
|
|
|
url
|
|
|
|
end
|
2008-06-20 23:26:26 +02:00
|
|
|
end
|
2008-03-18 19:37:10 +01:00
|
|
|
end
|