Skip to content

Instantly share code, notes, and snippets.

@chrise86
Forked from mperham/after.rb
Created July 25, 2017 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrise86/f5f7c04ec47419163f521de6c0787214 to your computer and use it in GitHub Desktop.
Save chrise86/f5f7c04ec47419163f521de6c0787214 to your computer and use it in GitHub Desktop.
Thread-friendly shared connection
class ActiveRecord::Base
mattr_accessor :shared_connection
@@shared_connection = nil
def self.connection
@@shared_connection || ConnectionPool::Wrapper.new(:size => 1) { retrieve_connection }
end
end
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
class ActiveRecord::Base
mattr_accessor :shared_connection
@@shared_connection = nil
def self.connection
@@shared_connection || retrieve_connection
end
end
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
Capybara uses two threads to run client and server. If you just cargo cult
the DatabaseCleaner code that is floating around, you can run into
https://github.com/brianmario/mysql2/issues/99 because the threads will
occasionally use the same connection at the same time.
The fix is to use a single connection but protect access to it by having each
thread "check out" the connection when they are using it. This is trivial to
do with the `connection_pool` gem. Add it to your Gemfile and use the "after"
code above.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment