kovyrin/db-charmer — pull request #86 by perplexes (2013-12-06 18:56:28+00:00)
Title: Allow AR::B.db_magic m/s split to work with abstract AR classes.

Hi, ran into a SystemStackError. We wanted to split all reads in all models to slaves. The easiest way to do this seemed like:

In config/initializers/db_charmer.rb:
```ruby
ActiveRecord::Base.db_magic(slave: :main_slave)
```

But we also have Rails Engines that have their own version of an AR::B-like class with a separate connection, called base:

```ruby
class IsbnDb::Base < ActiveRecord::Base
self.abstract_class = true
db_magic connection: :isbn_master, slave: :isbn_slave
end
```

Then models underneath that would inherit this connection:
```ruby
class Isbn < IsbnDb::Base
end
```

What we were seeing were SystemStackErrors:

```ruby
[3] pry(main)> Isbn.first
SystemStackError: stack level too deep
```

After a lot of tracing (and set_trace_func), the culprit is that putting db_magic on ActiveRecord::Base overrides the default behavior of the master/slave automatic methods like reload, find_by_sql and count_by_sql. In models that directly inherit from AR::B (like User, say) this behavior is fine - but in level-2 inherited models (AR::B > Base > Isbn), is causes infinite recursion.

This pull request fixes this situation, but I don't quite know how to test it.