Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Created December 10, 2020 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emad-elsaid/174d58f910ae494252bb945cd4868a82 to your computer and use it in GitHub Desktop.
Save emad-elsaid/174d58f910ae494252bb945cd4868a82 to your computer and use it in GitHub Desktop.
rails_explain_sql_initializer
class Explainer < ActiveSupport::LogSubscriber
def sql(event)
payload = event.payload
return if ignore_payload?(payload)
debug color(ActiveRecord::Base.connection.explain(payload[:sql], payload[:binds]), :yellow)
end
private
IGNORED_PAYLOADS = %w[SCHEMA EXPLAIN].freeze
EXPLAINED_SQLS = /\A\s*(with|select|update|delete|insert)\b/i.freeze
def ignore_payload?(payload)
payload[:cached] ||
IGNORED_PAYLOADS.include?(payload[:name]) ||
payload[:sql] !~ EXPLAINED_SQLS
end
end
Explainer.attach_to :active_record
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment