File: transaction_commands.rb

package info (click to toggle)
ruby-fakeredis 0.8.0-7
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 628 kB
  • sloc: ruby: 4,868; makefile: 2
file content (83 lines) | stat: -rw-r--r-- 1,667 bytes parent folder | download | duplicates (2)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
module FakeRedis
  TRANSACTION_COMMANDS = [:discard, :exec, :multi, :watch, :unwatch, :client]

  module TransactionCommands
    def self.included(klass)
      klass.class_eval do
        def self.queued_commands
          @queued_commands ||= Hash.new {|h,k| h[k] = [] }
        end

        def self.in_multi
          @in_multi ||= Hash.new{|h,k| h[k] = false}
        end

        def queued_commands
          self.class.queued_commands[database_instance_key]
        end

        def queued_commands=(cmds)
          self.class.queued_commands[database_instance_key] = cmds
        end

        def in_multi
          self.class.in_multi[database_instance_key]
        end

        def in_multi=(multi_state)
          self.class.in_multi[database_instance_key] = multi_state
        end
      end
    end

    def discard
      unless in_multi
        raise Redis::CommandError, "ERR DISCARD without MULTI"
      end

      self.in_multi = false
      self.queued_commands = []

      'OK'
    end

    def exec
      unless in_multi
        raise Redis::CommandError, "ERR EXEC without MULTI"
      end

      responses  = queued_commands.map do |cmd|
        begin
          send(*cmd)
        rescue => e
          e
        end
      end

      self.queued_commands = [] # reset queued_commands
      self.in_multi = false     # reset in_multi state

      responses
    end

    def multi
      if in_multi
        raise Redis::CommandError, "ERR MULTI calls can not be nested"
      end

      self.in_multi = true

      yield(self) if block_given?

      "OK"
    end

    def watch(*_)
      "OK"
    end

    def unwatch
      "OK"
    end
  end
end