summaryrefslogtreecommitdiff
path: root/spec/support/helpers/redis_commands/recorder.rb
blob: 05a1aa6785396814b8bf00559fcc4d966f3cd047 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# frozen_string_literal: true

module RedisCommands
  class Recorder
    def initialize(pattern: nil, &block)
      @log = []
      @pattern = pattern

      record(&block) if block
    end

    attr_reader :log

    def record(&block)
      ActiveSupport::Notifications.subscribed(method(:callback), 'redis.process_commands', &block)
    end

    def by_command(command)
      @log.select { |record| record.include?(command) }
    end

    def count
      @count ||= @log.count
    end

    private

    def callback(name, start, finish, message_id, values)
      commands = values[:commands]

      @log << commands.flatten if @pattern.nil? || commands.to_s.include?(@pattern)
    end
  end
end