Skip to content

Instantly share code, notes, and snippets.

@adstage-david
Forked from jrochkind/gist:1364551
Created January 30, 2015 21:57

Revisions

  1. adstage-david revised this gist Jan 30, 2015. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -29,3 +29,6 @@ def thread_connected?
    class ImplicitConnectionForbiddenError < ActiveRecord::ConnectionTimeoutError ; end

    end

    ActiveRecord::Base.forbid_implicit_checkout_for_thread!
    ActiveRecord::Base.connection_pool.checkin(ActiveRecord::Base.connection_pool.connections.first)
  2. @jrochkind jrochkind created this gist Nov 14, 2011.
    31 changes: 31 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    # 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