Skip to content

Instantly share code, notes, and snippets.

@palkan
Created March 7, 2017 09:28
Show Gist options
  • Save palkan/98214019355b6061319769e9efef5eda to your computer and use it in GitHub Desktop.
Save palkan/98214019355b6061319769e9efef5eda to your computer and use it in GitHub Desktop.
ActiveRecord OneLove
module ActiveRecord
# Share connection between threads to make it possible to wrap system tests in a transaction.
# Also synchonize queries to avoid concurrent writes/reads.
#
# For PostgreSQL adapter.
module OneLove
class << self
attr_reader :connection
def connection=(conn)
@connection = conn
connection.singleton_class.prepend Connection
connection
end
end
module Connection
@@mutex = Mutex.new
def exec_cache(*)
@@mutex.synchronize { super }
end
def exec_no_cache(*)
@@mutex.synchronize { super }
end
def execute(*)
@@mutex.synchronize { super }
end
end
module Ext
def connection
OneLove.connection || super
end
end
end
end
ActiveSupport.on_load(:active_record) do
ActiveRecord::OneLove.connection = ActiveRecord::Base.connection
ActiveRecord::Base.singleton_class.prepend ActiveRecord::OneLove::Ext
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment