@RicRoberts on Twitter: My latest tweet should appear here. If you can read this, it means Twitter is down or being slow.

RIC ROBERTS

Web Developer and founder of Swirrl.com

Using a different Couch DB for each web-request with CouchRest

If data for each different account in your web application is stored in a separate CouchDB database, you need a way to tell your web app which database to use for that request.

Here’s solution using CouchRest and Ruby, based on a discussion from the CouchRest Google Group.

class RequestSpecificDocument < CouchRest::ExtendedDocument
  def self.database
    Thread.current[:request_db]
  end
end

All models which need to use the request-specific database should derive from this:

class Article < RequestSpecificDocument
  # normal stuff for your CouchRest document here.
end

So in your application controller (if you’re using Rails), you might add a before_filter which does something like this:

def set_database
  # determine the database_name from the host, url or whatever. 
  svr = CouchRest::Server.new("http://127.0.0.1:5984")
  couch_db = CouchRest::Database.new(svr, database_name)        
  Thread.current[:request_db] = couch_db
end
blog comments powered by Disqus