-
Notifications
You must be signed in to change notification settings - Fork 29
/
playable.rb
89 lines (69 loc) · 1.83 KB
/
playable.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# frozen_string_literal: true
# Play class method to call a series of actors with the same result. On failure,
# calls rollback on actors that succeeded.
#
# class CreateUser < Actor
# play SaveUser,
# CreateSettings,
# SendWelcomeEmail
# end
module ServiceActor::Playable
def self.included(base)
base.extend(ClassMethods)
base.prepend(PrependedMethods)
end
module ClassMethods
def play(*actors, **options)
play_actors.push(actors: actors, **options)
end
def play_actors
@play_actors ||= []
end
def inherited(child)
super
child.play_actors.concat(play_actors)
end
end
module PrependedMethods
def call
self.class.play_actors.each do |options|
next if options[:if] && !options[:if].call(result)
options[:actors].each { |actor| play_actor(actor) }
end
rescue self.class.failure_class
rollback
raise
end
def rollback
return unless defined?(@played_actors)
@played_actors.each do |actor|
next unless actor.respond_to?(:rollback)
actor.rollback
end
end
private
def play_actor(actor)
play_service_actor(actor) ||
play_method(actor) ||
play_interactor(actor) ||
actor.call(result)
end
def play_service_actor(actor)
return unless actor.is_a?(Class)
return unless actor.ancestors.include?(ServiceActor::Core)
actor = actor.new(result)
actor._call
(@played_actors ||= []).unshift(actor)
end
def play_method(actor)
return unless actor.is_a?(Symbol)
send(actor)
true
end
def play_interactor(actor)
return unless actor.is_a?(Class)
return unless actor.ancestors.map(&:name).include?("Interactor")
result.merge!(actor.call(result).to_h)
end
end
end