Last Modified
2013-07-31 01:34:14 +0000
Requires

Description

The server_block extension adds the Database#with_server method, which takes a shard argument and a block, and makes it so that access inside the block will use the specified shard by default.

First, you need to enable it on the database object:

DB.extension :server_block

Then you can call with_server:

DB.with_server(:shard1) do
  DB[:a].all # Uses shard1
  DB[:a].server(:shard2).all # Uses shard2
end
DB[:a].all # Uses default

You can even nest calls to with_server:

DB.with_server(:shard1) do
  DB[:a].all # Uses shard1
  DB.with_server(:shard2) do
    DB[:a].all # Uses shard2
  end
  DB[:a].all # Uses shard1
end
DB[:a].all # Uses default

Note this this extension assumes the following shard names should use the server/shard passed to with_server: :default, nil, :read_only. All other shard names will cause the standard behavior to be used.