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

49 lines
1.6 KiB
Ruby

module JamRuby
class BaseManager
attr_accessor :pg_conn
@@in_websocket_gateway = Rails.env != 'test' && !Object.const_defined?(:UserManager)
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
def self.active_record_transaction
manager = self.new
@log.debug("DEBUGCONN -1")
ActiveRecord::Base.connection_pool.with_connection do |connection|
@log.debug("DEBUGCONN -2")
# 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.
manager.pg_conn = connection.instance_variable_get("@connection")
if @@in_websocket_gateway
@log.debug("DEBUGCONN -3")
# 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
yield manager
end
rescue Exception => e
ActiveRecord::Base.connection.execute('ROLLBACK')
end
else
@log.debug("DEBUGCONN -4")
connection.transaction do
@log.debug("DEBUGCONN -5")
yield manager
end
end
end
end
end
end