Sha256: 9b2ba254a11cf0c41307a19dd95d6b02af92da8cd17d596e8e9d2dcf7ea2384a

Contents?: true

Size: 1.15 KB

Versions: 1

Compression:

Stored size: 1.15 KB

Contents

# frozen_string_literal: true

require 'rails_sql_counter/version'

# Count sql queries
module RailsSqlCounter
  mattr_accessor :backtrace, default: false
  mattr_accessor :backtrace_regex, default: /(action|active|pry|rack|puma|rspec|bundle)/

  def self.setup
    yield self
  end

  def self.process(event)
    return unless event.payload[:name]&.match?('Load') && Thread.current[:rails_sql_counter]

    inc
    show_backtrace if @@backtrace
  end

  def self.inc
    Thread.current[:rails_sql_counter] += 1
  end

  def self.start
    Thread.current[:rails_sql_counter] = 0

    @@subscriber ||= ActiveSupport::Notifications.subscribe('sql.active_record') do |event|
      process(event)
    end
  end

  def self.end
    Thread.current[:rails_sql_counter] = nil

    ActiveSupport::Notifications.unsubscribe(@@subscriber)
    @@subscriber = nil
  end

  def self.counter
    Thread.current[:rails_sql_counter]
  end

  def self.show_backtrace
    # remove first two entries (gem entries)
    caller.drop(2).each do |line|
      next if line.match?(@@backtrace_regex)

      Rails.logger.debug "    -> #{line}"
    end
  end

  private_class_method :inc, :show_backtrace
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rails_sql_counter-0.1.1 lib/rails_sql_counter.rb