Skip to content

Instantly share code, notes, and snippets.

@jrochkind
Created November 14, 2011 17:35
Show Gist options
  • Save jrochkind/1364551 to your computer and use it in GitHub Desktop.
Save jrochkind/1364551 to your computer and use it in GitHub Desktop.
REALLY hacky monkey patch to AR to prohibit implicit connection checkout
# Call ActiveRecord::base.forbid_implicit_checkout_for_thread! from a thread, and if
# that thread later tries to access an active record connection without explicit checkout
# (#with_connection, or #checkout), an ImplicitConnectionForbiddenError will be raised.
module ActiveRecord
class Base
class << self
def forbid_implicit_checkout_for_thread!
Thread.current[:active_record_forbid_implicit_connections] = true
end
def connection
if Thread.current[:active_record_forbid_implicit_connections] && ! thread_connected?
raise ImplicitConnectionForbiddenError.new("Implicit ActiveRecord checkout attempted when Thread :force_explicit_connections set!")
end
retrieve_connection
end
# In Rails 3.1, this is connection_pool.active_connection?
# But we define our own so we have it in Rails 3.0 too.
def thread_connected?
connection_id = connection_pool.send(:current_connection_id)
connection_pool.instance_variable_get("@reserved_connections").has_key? connection_id
end
end
end
class ImplicitConnectionForbiddenError < ActiveRecord::ConnectionTimeoutError ; end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment