Skip to content

Instantly share code, notes, and snippets.

@joeywang
Created June 7, 2025 21:25
Show Gist options
  • Save joeywang/fe2f6be7ca0bfcf6d3f0c8409acd1d32 to your computer and use it in GitHub Desktop.
Save joeywang/fe2f6be7ca0bfcf6d3f0c8409acd1d32 to your computer and use it in GitHub Desktop.
# file: config/initializers/connection_validation_test.rb
# This block will be executed only after Active Record has finished loading.
ActiveSupport.on_load(:active_record) do
  # Within this block, it's now safe to modify Active Record components.
  module ActiveRecord
    module ConnectionAdapters
      # It's good practice to check if the class is defined to avoid errors
      # in environments where it might not be (e.g., if you switched to MySQL).
      if defined?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter)
        class PostgreSQLAdapter
          # A simple way to log and confirm your patch is working.
          # Using a logger is better than puts.
          Rails.logger.info '-'*100
          Rails.logger.info "Monkey-patching ActiveRecord::ConnectionAdapters::PostgreSQLAdapter to instrument active? check."

          # Now, this alias will work because active? is guaranteed to be defined.
          alias_method :original_active?, :active?

          # Define your new version of the method.
          def active?(*args)
            # Add your custom logic/logging here.
            Rails.logger.info "====> Custom check: Verifying connection with active? <===="

            # Call the original method to preserve its functionality.
            # The return value of this line will be the return value of your new active? method.
            original_active?(*args)
          end
        end
      end
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment