summaryrefslogtreecommitdiff
path: root/lib/killjoy/rmq/message.rb
blob: 2aa9c7dd23e2d9978c7effa84ce89761935f5945 (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
35
36
37
38
39
40
41
42
43
44
45
46
47
module Killjoy
  class Message
    attr_reader :to_hash, :info, :channel

    def initialize(raw_message, info, channel)
      @to_hash = JSON.parse(raw_message, symbolize_names: true)
      @info = info
      @channel = channel
      @interceptors = { ack: [], reject: [] }
    end

    def intercept(response_type, &block)
      @interceptors[response_type] << block
    end

    def process(future)
      future.on_success do |rows|
        ack!
      end
      future.on_failure do |error|
        reject!
      end
    end

    def ack!
      run_interceptors_for(:ack)
      channel.acknowledge(info.delivery_tag, false)
    end

    def reject!(requeue = false)
      run_interceptors_for(:reject)
      channel.reject(info.delivery_tag, requeue)
    end

    def to_s
      to_hash
    end

    private

    def run_interceptors_for(response_type)
      @interceptors[response_type].each do |interceptor|
        interceptor.call
      end
    end
  end
end