Skip to content

Instantly share code, notes, and snippets.

@lujanfernaud
Last active August 10, 2018 07:28
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 lujanfernaud/5de194816070c2ee71a182ab845e7903 to your computer and use it in GitHub Desktop.
Save lujanfernaud/5de194816070c2ee71a182ab845e7903 to your computer and use it in GitHub Desktop.
Rails: Strict Queries
# frozen_string_literal: true
# Alerts of SQL queries made within views.
#
# https://www.driftingruby.com/episodes/improving-partial-loading-performance
module StrictQueries
class SQLWithViewError < StandardError; end
module Concern
extend ActiveSupport::Concern
included do
def render(*args, &block)
return super if production?
callback = lambda do |name, start, finish, id, payload|
if !should_ignore_sql_statement?(payload[:name])
raise SQLWithViewError.new(message(payload[:sql]))
end
end
ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
super
end
end
private
def production?
Rails.env.production?
end
def should_ignore_sql_statement?(name)
["SCHEMA", "ActionRecord::SchemaMigration Load"].include?(name)
end
def message(sql)
"A SQL request was issued within the view:\n#{sql}"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment