Module: CouchFoo::Database::ClassMethods

Defined in:
lib/couch_foo/database.rb

Instance Method Summary collapse

Instance Method Details

#databaseObject

Get the current database



131
132
133
134
135
136
137
138
139
140
141
# File 'lib/couch_foo/database.rb', line 131

def database
  if @active_database.nil?
    if self == CouchFoo::Base
      raise CouchFooError, "No databases setup"
    else
      superclass.database
    end
  else
    @active_database
  end
end

#set_database(options, bulk_save = bulk_save_default) ⇒ Object

Set the database to be used with this model. This honours inheritence so sub-classes can use different databases from their parents. As such if you only use one database for your application then only one call is required to CouchFoo::Base for initial setup.

When using a database for the first time a version check is performed on CouchDB so that performance optimisations are run according to your database version. At time of writing CouchDB 0.9 offers some good performance gains over 0.8

For ultra-scalability and using a different database for each user, perform the set_database call on the CouchFoo::Base object on a before_filter using the session information to determine the database to connect to. For example:

class ApplicationController < ActionController::Base

before_filter :set_user_database

def set_user_database
  CouchFoo::Base.set_database(:host => "http://localhost:5984", :database => "user#{session[:user]}")
end

end

As the need grows to move user databases onto different servers (sharding) then you can either:<ul> <li>create a lookup file/database that maps user_id to database location</li> <li>locate the database servers behind apache (or equivalent) using rewrite rules. The server

knows which users live on which physical machine and rewrites accordingly.  Thus only one 
database url is required at the application level)</li>

</ul>

NOTE: This will work best on domains where there is little overlap between users data (eg basecamp)



172
173
174
# File 'lib/couch_foo/database.rb', line 172

def set_database(options, bulk_save = bulk_save_default)
  @active_database = DatabaseWrapper.new(options, bulk_save)
end