Created
December 2, 2015 08:58
-
-
Save tobiashm/c40c942b48e8a13b9418 to your computer and use it in GitHub Desktop.
Handle connection for ActiveRecord subclasses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require "active_record/base" | |
| module ConnectionHandler | |
| class << self | |
| def establish_connections | |
| connection_classes.each(&:establish_connection) | |
| end | |
| def disconnect_all! | |
| connection_classes.map(&:connection).each(&:disconnect!) | |
| end | |
| private | |
| def connection_classes | |
| [ActiveRecord::Base] + base_classes_with_own_connection | |
| end | |
| def base_classes_with_own_connection | |
| ActiveRecord::Base.subclasses.select do |klass| | |
| klass.method(:establish_connection).owner == (class << klass; self; end) | |
| end | |
| end | |
| end | |
| end |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you have multiple database connection using ActiveRecord, it's a good practice to define a base class for each connection which overrides the
establish_connectionmethod. In this way, all models that uses this will reuse the same connection. Otherwise each model will create its own connection.If you get more of these, it quickly get cumbersome to handle disconnecting and reconnecting in forking applications like Unicorn or Resque. This class wraps the handling of this, so you only need one call.