-
-
Save bbugh/1508641875bd7521b14014e4b38bf4d5 to your computer and use it in GitHub Desktop.
Profile ActiveRecord queries, output Markdown table of counts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Originally referenced from https://medium.com/treehouse-engineering/continous-improvements-4741fc3c7daa | |
RSpec.configure do |config| | |
config.before(:suite) do | |
Thread.current[:query_counter] = Hash.new(0) | |
end | |
config.around(:example) do |procsy| | |
callback = lambda do |*args| | |
event = ActiveSupport::Notifications::Event.new(*args) | |
sql = event.payload[:sql].to_s.strip | |
operation = sql.split(' ', 2).first.to_s.downcase | |
next if operation.blank? | |
next if event.payload[:name] == "SCHEMA" | |
next if event.payload[:name].nil? | |
Thread.current[:query_counter][procsy.location] += 1 | |
end | |
ActiveSupport::Notifications.subscribed(callback, "sql.active_record") { procsy.run } | |
end | |
config.after(:suite) do | |
puts | |
puts "ActiveRecord queries performed:\n" | |
sorted = Thread.current[:query_counter].sort_by { |_location, count| count }.reverse | |
puts "| Location | Queries |" | |
puts "| -------- | ------- |" | |
sorted.each do |location, count| | |
puts "| #{location} | #{count} |" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment