README.md in slavery-1.1.1 vs README.md in slavery-1.2.0

- old
+ new

@@ -20,26 +20,37 @@ And create slave configs for each environment. ```yaml development: - adapter: mysql2 - username: root database: myapp_development development_slave: - adapter: mysql2 - username: root database: myapp_development ``` By convention, config keys with `[env]_slave` are automatically used for slave reads. Notice that we just copied the settings of `development` to `development_slave`. For `development` and `test`, it's actually recommended as probably you don't want to have replicating multiple databases on your machine. Two connections to the same identical database should be fine for testing purpose. -At this point, Slavery does nothing. Run tests and confirm that anything isn't broken. +In case you prefer DRYer definition, YAML's aliasing and key merging might help. +```yaml +common: &common + adapter: mysql2 + username: root + database: myapp_development + +development: + <<: *common + +development_slave: + <<: *common +``` + +At this point, Slavery does nothing. Run tests and confirm that nothing is broken. + ## Usage To start using Slavery, you need to add `Slavery.on_slave` in your code. Queries in the `Slavery.on_slave` block run on the slave. ```ruby @@ -56,19 +67,26 @@ end ... end ``` +Alternatively, you may call `on_slave` directly on the scope, so that the query will be read from slave when it's executed. + +```ruby +User.on_slave.where(active: true).count +``` + +Caveat: `pluck` is not supported by the scope syntax, you still need `Slavery.on_slave` in this case. + ## Read-only user For an extra safeguard, it is recommended to use a read-only user for slave access. -```ruby +```yaml development_slave: - adapter: mysql2 + <<: *common username: readonly - database: myapp_development ``` With MySQL, `GRANT SELECT` creates a read-only user. ```SQL @@ -79,10 +97,10 @@ ```ruby Slavery.on_slave { User.create } # => ActiveRecord::StatementInvalid: Mysql2::Error: INSERT command denied... ``` -It is a good idea to confirm this behavior in your test code. +It is a good idea to confirm this behavior in your test code as well. ## Database failure When one of the master or the slave goes down, you would rewrite `database.yml` to make all queries go to the surviving database, until you restore or rebuild the failed one.