Class: DBQueryMatchers::QueryCounter

Inherits:
Object
  • Object
show all
Defined in:
lib/db_query_matchers/query_counter.rb

Overview

Counter to keep track of the number of queries caused by running a piece of code. Closely tied to the ‘:make_database_queries` matcher, this class is designed to be a consumer of `sql.active_record` events.

Examples:

counter = DBQueryMatchers::QueryCounter.new
ActiveSupport::Notifications.subscribed(counter.to_proc,
                                       'sql.active_record') do
  # run code here
end
puts counter.count          # prints the number of queries made
puts counter.log.join(', ') # prints all queries made

See Also:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeQueryCounter

Returns a new instance of QueryCounter.



19
20
21
22
# File 'lib/db_query_matchers/query_counter.rb', line 19

def initialize
  @count = 0
  @log   = []
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



17
18
19
# File 'lib/db_query_matchers/query_counter.rb', line 17

def count
  @count
end

#logObject (readonly)

Returns the value of attribute log.



17
18
19
# File 'lib/db_query_matchers/query_counter.rb', line 17

def log
  @log
end

Instance Method Details

#callback(_name, _start, _finish, _message_id, payload) ⇒ Object

Method called from the ActiveSupport::Notifications module (through the lambda created by ‘to_proc`) when an SQL query is made.

Parameters:

  • _name (String)

    name of the event

  • _start (Time)

    when the instrumented block started execution

  • _finish (Time)

    when the instrumented block ended execution

  • _message_id (String)

    unique ID for this notification

  • payload (Hash)

    the payload



40
41
42
43
44
45
46
# File 'lib/db_query_matchers/query_counter.rb', line 40

def callback(_name, _start,  _finish, _message_id, payload)
  return if DBQueryMatchers.configuration.ignores.any? do |pattern|
    payload[:sql] =~ pattern
  end
  @count += 1
  @log << payload[:sql]
end

#to_procProc

Turns a QueryCounter instance into a lambda. Designed to be used when subscribing to events through the ActiveSupport::Notifications module.

Returns:

  • (Proc)


28
29
30
# File 'lib/db_query_matchers/query_counter.rb', line 28

def to_proc
  lambda(&method(:callback))
end