README.markdown

masochism

The masochism plugin provides an easy solution for Ruby on Rails applications to work in a
replicated database environment. It works by replacing the connection object accessed by
ActiveRecord models by ConnectionProxy that chooses between master and slave when
executing queries. Generally all writes go to master.

# in environment.rb
config.after_initialize do
if Rails.env.production?
ActiveReload::ConnectionProxy::setup!
end
end

Considerations

Thinking Sphinx

Thinking Sphinx inspects the connection object to determine the database adapter.
Because masochism works by putting the connection proxy in its place, TS will get confused
about ActiveReload::ConnectionProxy and abort. A possible workaround is to monkeypatch
TS right to hardcode our adapter after masochism has been enabled:

# ConnectionProxy from masochism confuses TS
ThinkingSphinx::Index.class_eval do
def adapter() :mysql end
end
ThinkingSphinx::AbstractAdapter.class_eval do
def self.detect(model)
ThinkingSphinx::MysqlAdapter
end
end

In newer versions of Thinking Sphinx (observed in 1.1.3), different parts have to be patched:

Litespeed web server or Phusion Passenger (mod_rails)

If you are using the Litespeed web server or Passenger (mod_rails), child processes are initialized on creation,
which means any setup done in an environment file will be effectively ignored. A brief
discussion of the problem is posted here.

One solution for Litespeed/Passenger users is to check the connection at your first request and do
the setup! call if your connection hasn't been initialized, like:

# in ApplicationController
prepend_before_filter do |controller|
unless ActiveRecord::Base.connection.is_a? ActiveReload::ConnectionProxy
ActiveReload::ConnectionProxy.setup!
end
end

Advanced

The ActiveReload::MasterDatabase and ActiveReload::SlaveDatabase abstract models use the
'master_database' and 'slave_database' settings, respectively.

In 'database.yml' configuration file, both settings can be specified either per-environment or
global (like in the first example of this document).

More control at setup

The first argument is the model that has the master database connection established; the
second argument is the model whose connection gets hijacked by ConnectionProxy. But we
don't have to touch ActiveRecord::Base at all:

# set up MyMaster's connection as the master database connection for User:
ActiveReload::ConnectionProxy.setup_for MyMaster, User

The controller filter

If you have any actions you know require the master database for both reads and writes,
simply do the following: