I needed to see all plans for the executed SQL statements in my rails project while in development. so I found this Gem
repository
I want to understand how it works, and found that the main piece of code is in this file so I tried to get this code and simplify it and add it to an initializer and the result is the following stripped down version
1class Explainer < ActiveSupport::LogSubscriber
2 def sql(event)
3 payload = event.payload
4 return if ignore_payload?(payload)
5
6 debug color(ActiveRecord::Base.connection.explain(payload[:sql], payload[:binds]), :yellow)
7 end
8
9 private
10
11 IGNORED_PAYLOADS = %w[SCHEMA EXPLAIN].freeze
12 EXPLAINED_SQLS = /\A\s*(with|select|update|delete|insert)\b/i.freeze
13
14 def ignore_payload?(payload)
15 payload[:cached] ||
16 IGNORED_PAYLOADS.include?(payload[:name]) ||
17 payload[:sql] !~ EXPLAINED_SQLS
18 end
19end
20
21Explainer.attach_to :active_record
Just make sure you don’t commit this code or put a condition at the last line to work only in development.