module MyStuff::MultiDB
Example¶ ↑
module Foo class SomeTable < ActiveRecord::Base end include MyStuff::MultiDB::Unsharded end module Bar class SomeTable < ActiveRecord::Base end include MyStuff::MultiDB::Sharded end Foo.with_master do |db| p db::SomeTable.where(:some_column = 'bar') end Foo.with_slave do |db| p db::SomeTable.where(:some_column = 'bar') end Bar.with_master_for(id) do |db| p db::SomeTable.where(:some_column = 'bar') end Bar.with_master_for_new do |db| db::SomeTable.new do ... end end Bar.with_slave_for(id) do |db| p db::SomeTable.where(:some_column = 'bar') end
See MyStuff::MultiDB::Unsharded
and MyStuff::MultiDB::Sharded
Details¶ ↑
When you call with_*
, it:
-
Looks for a class called MyStuff::MultiDB::MANGLED_DATABASE_NAME
-
If it doesn’t exist, it creates a new ActiveRecord::Base subclass
-
It then looks for a module within that class with the same name as your module
-
If it’s not there:
-
It creates the module
-
It creates a subclass of each of your ActiveRecord definitions within this module
-
It delegates connection handling to the database class
-
-
It then returns the database class
So, you end up with an ActiveRecord class like: MyStuff::MultiDB::MANGLED_DATABASE_NAME::YourModule::YourClass