Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Created December 2, 2015 08:58
Show Gist options
  • Select an option

  • Save tobiashm/c40c942b48e8a13b9418 to your computer and use it in GitHub Desktop.

Select an option

Save tobiashm/c40c942b48e8a13b9418 to your computer and use it in GitHub Desktop.
Handle connection for ActiveRecord subclasses
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
@tobiashm
Copy link
Copy Markdown
Author

tobiashm commented Dec 2, 2015

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_connection method. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment