/
rotator.rb
59 lines (51 loc) · 1.5 KB
/
rotator.rb
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
# frozen_string_literal: true
module ActiveSupport
module Messages
module Rotator # :nodoc:
def initialize(*args, on_rotation: nil, **options)
super(*args, **options)
@args = args
@options = options
@rotations = []
@on_rotation = on_rotation
end
def rotate(*args, **options)
fall_back_to build_rotation(*args, **options)
end
def fall_back_to(fallback)
@rotations << fallback
self
end
def read_message(message, on_rotation: @on_rotation, **options)
if @rotations.empty?
super(message, **options)
else
thrown, error = catch_rotation_error do
return super(message, **options)
end
@rotations.each do |rotation|
catch_rotation_error do
value = rotation.read_message(message, **options)
on_rotation&.call
return value
end
end
throw thrown, error
end
end
private
def build_rotation(*args, **options)
self.class.new(*args, *@args.drop(args.length), **@options, **options)
end
def catch_rotation_error(&block)
error = catch :invalid_message_format do
error = catch :invalid_message_serialization do
return [nil, block.call]
end
return [:invalid_message_serialization, error]
end
[:invalid_message_format, error]
end
end
end
end