Created
March 7, 2017 09:28
-
-
Save palkan/98214019355b6061319769e9efef5eda to your computer and use it in GitHub Desktop.
ActiveRecord OneLove
This file contains 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
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