The official documentation has moved to http://docs.couchdb.org — The transition is not 100% complete, but http://docs.couchdb.org should be seen as having the latest info. In some cases, the wiki still has some more or older info on certain topics inside CouchDB.

You need to be added to the ContributorsGroup to edit the wiki. But don't worry! Just email any Mailing List or grab us on IRC and let us know your user name.

Getting started with Ruby and the CouchDB API.

The following shows the basics of working with the raw CouchDB REST api from Ruby. If you want a richer interface that more tightly maps Couch documents into Ruby and also lets you save ruby objects directly to the database, you should check out the RubyLibrary.

Example Wrapper Class

   1 require 'net/http'
   2 
   3 module Couch
   4 
   5   class Server
   6     def initialize(host, port, options = nil)
   7       @host = host
   8       @port = port
   9       @options = options
  10     end
  11 
  12     def delete(uri)
  13       request(Net::HTTP::Delete.new(uri))
  14     end
  15 
  16     def get(uri)
  17       request(Net::HTTP::Get.new(uri))
  18     end
  19 
  20     def put(uri, json)
  21       req = Net::HTTP::Put.new(uri)
  22       req["content-type"] = "application/json"
  23       req.body = json
  24       request(req)
  25     end
  26 
  27     def post(uri, json)
  28       req = Net::HTTP::Post.new(uri)
  29       req["content-type"] = "application/json"
  30       req.body = json
  31       request(req)
  32     end
  33 
  34     def request(req)
  35       res = Net::HTTP.start(@host, @port) { |http|http.request(req) }
  36       unless res.kind_of?(Net::HTTPSuccess)
  37         handle_error(req, res)
  38       end
  39       res
  40     end
  41 
  42     private
  43 
  44     def handle_error(req, res)
  45       e = RuntimeError.new("#{res.code}:#{res.message}\nMETHOD:#{req.method}\nURI:#{req.path}\n#{res.body}")
  46       raise e
  47     end
  48   end
  49 end

Creating a Database

To create a database called foo:

server = Couch::Server.new("localhost", "5984")
server.put("/foo/", "")

Deleting a Database

To delete a database called foo:

server = Couch::Server.new("localhost", "5984")
server.delete("/foo")

Creating a Document

To create a document in the database foo with the id document_id:

server = Couch::Server.new("localhost", "5984")
doc = <<-JSON
{"type":"comment","body":"First Post!"}
JSON
server.put("/foo/document_id", doc)

Reading a Document

To read a document from database foo with the id document_id:

server = Couch::Server.new("localhost", "5984")
res = server.get("/foo/document_id")
json = res.body
puts json

Getting_started_with_Ruby (last edited 2011-11-23 14:54:11 by JanLehnardt)