jam-cloud/ruby/lib/jam_ruby/base_manager.rb

50 lines
1.6 KiB
Ruby
Raw Permalink Normal View History

2012-11-12 12:28:44 +00:00
module JamRuby
class BaseManager
attr_accessor :pg_conn
2016-03-25 18:49:53 +00:00
@@log = Logging.logger[BaseManager]
# this is not working as expected
#@@in_websocket_gateway = Rails.env != 'test' && !Object.const_defined?(:UserManager)
@@in_websocket_gateway = false
2012-11-12 12:28:44 +00:00
def initialize(options={})
@log = Logging.logger[self]
@pg_conn = options[:conn]
unless PG.threadsafe?
raise Exception, "a non-threadsafe build of libpq is present."
end
end
# Creates a connection manager, and associates the connection created by active_record with ourselves
2012-11-30 09:34:50 +00:00
def self.active_record_transaction
2012-11-12 12:28:44 +00:00
manager = self.new
ActiveRecord::Base.connection_pool.with_connection do |connection|
# create a transaction, and pass the current connection to ConnectionManager.
# this lets the entire operation work with the same transaction,
# across Rails ActiveRecord and the pg-gem based code in ConnectionManager.
2020-12-27 23:58:31 +00:00
conn = connection.instance_variable_get("@connection")
manager.pg_conn = conn
2012-11-12 12:28:44 +00:00
if @@in_websocket_gateway
# it only necessary to catch exceptions in websocket-gateway, which has only one AR connection and does not clean it up like a Rails context does
begin
connection.transaction do
2020-12-27 23:58:31 +00:00
yield manager, conn
end
rescue Exception => e
ActiveRecord::Base.connection.execute('ROLLBACK')
end
else
2016-01-29 22:00:00 +00:00
connection.transaction do
2020-12-27 23:58:31 +00:00
yield manager, conn
2016-01-29 22:00:00 +00:00
end
2012-11-12 12:28:44 +00:00
end
end
end
end
end