Welcome to slaver!
It's a simple gem for rails application within multi-database environment. It allows you to change your current connection to other database configuration. Some ideas was inspired by octopus.
It was tested only on rails 3
and ruby 1.9.3
. Other configurations may work or may not:)
Add this line to your application's Gemfile:
gem 'slaver'
And then execute:
$ bundle
Or install it yourself as:
$ gem install slaver
You must have other connection on your database.yml file. For example:
production:
adapter: pg
host: master
database: master
post: 11111
production_slave:
adapter: sqlite3
host: slave
database: slave
post: 11113
production_mysql:
adapter: mysql
user: me
host: somewhere_else
post: 11112
database: mysql
Only works with class/scope methods. Connection changed until query is perfomed. After that it'll swiched back to default connection.
SomeModel.on(:production_mysql).where(name: 'me').first
# or, if you name starting with you Rails.env it can be skipped
SomeModel.on(:mysql).where(name: 'me').to_a
Connection will be switched for any query in block.
# simple usage
SomeModel.within(:slave) do
SomeModel.where(name: 'me')
end
# It also can be combined with "on" method
SomeModel.within(:mysql) do
me = SomeModel.find_by_name('me')
SomeModel.on(:slave).find_by_name('me').update_attributes(me.attributes)
end
# it can execute multi-models queries on other connection
ActiveRecord::Base.within(:slave) do
SomeModel.where(name: 'me').first
OtherModel.where(name: 'me').first
end
class Some
extend Slavable
def some_method
Foo.create
f = Foo.where(...).first
other = SomeModel.where(...).first
f.update_attributes(...)
other.update_attributes(...)
...
end
def self.class_method
b = Bar.create
b.update_attributes(...)
Foo.where(bar: b)
....
end
switch :some_method, to: :other
# it also can be called on multiple methods and works with class_methods
switch :some_method, ..., to: :other
# for switching class method just use singleton class pattern:
class << self
extend Slavable
switch :class_method, ..., to: :other
end
....
end
# it''ll be executed with :other connection
Some.class_method
Some.new.some_method
If you connection does not exists, behavior may change dependent of you current Rails environment:
Rails.env == production
: It'll raiseArgumentError
- otherwise: It'll try to switch to default connection -
Rails.env
- 'on' with assosiations
- Transaction safety
on
method on instance
To run test on local machine use make
command. For more info please reffer to Makefile.
- Fork it ( https://github.com/abak-press/slaver/fork )
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create new Pull Request
The gem is available as open source under the terms of the MIT License.