-
Notifications
You must be signed in to change notification settings - Fork 3
/
interaction.rb
112 lines (102 loc) · 2.08 KB
/
interaction.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
require "interaction/version"
require "interaction/params"
require "interaction/validation_helpers"
module Interaction
# Override Ruby's module inclusion hook to prepend base with #perform,
# extend base with a .perform method, and include Params for Virtus.
#
# @api private
def self.included(base)
base.class_eval do
prepend Perform
extend ClassMethods
include Params
end
end
module Perform
# Executes use case logic
#
# Use cases must implement this method. Assumes success if failure is not
# called.
#
# @since 0.0.1
# @api public
def perform
catch :halt do
super.tap do
success unless result_specified?
end
end
end
end
module ClassMethods
# Executes and returns the use case
#
# A use case object is instantiated with the supplied
# arguments, perform is called and the object is returned.
#
# @param args [*args] Arguments to initialize the use case with
#
# @return [Object] returns the use case object
#
# @since 0.0.1
# @api public
def perform(*args)
new(*args).tap do |use_case|
use_case.perform
end
end
end
# Indicates if the use case was successful
#
# @return [TrueClass, FalseClass]
#
# @since 0.0.1
# @api public
def success?
!!@success
end
# Indicates whether the use case failed
#
# @return [TrueClass, FalseClass]
#
# @since 0.0.1
# @api public
def failed?
!success?
end
private
# Mark the use case as successful.
#
# @return [TrueClass]
#
# @since 0.0.1
# @api public
def success
@success = true
end
# Mark the use case as failed.
#
# @since 0.0.1
# @api public
def failure
@success = false
end
# Mark the use case as failed and exits the use case.
#
# @since 0.0.1
# @api public
def failure!
failure
throw :halt
end
# Indicates whether the use case called success or failure
#
# @return [TrueClass, FalseClass]
#
# @api private
# @since 0.0.1
def result_specified?
defined?(@success)
end
end