Module: SolidUseCase::Either
- Defined in:
- lib/solid_use_case/either.rb,
lib/solid_use_case/either/error_struct.rb,
lib/solid_use_case/either/class_methods.rb
Defined Under Namespace
Modules: ClassMethods
Classes: ErrorStruct
Class Method Summary
collapse
Instance Method Summary
collapse
Class Method Details
.failure(type, data = {}) ⇒ Object
79
80
81
82
|
# File 'lib/solid_use_case/either.rb', line 79
def self.failure(type, data={})
data[:type] = type
Failure(ErrorStruct.new(data))
end
|
.success(value) ⇒ Object
75
76
77
|
# File 'lib/solid_use_case/either.rb', line 75
def self.success(value)
Success(value)
end
|
Instance Method Details
#attempt ⇒ Object
51
52
53
54
55
|
# File 'lib/solid_use_case/either.rb', line 51
def attempt
attempt_all do
try { yield }
end
end
|
#catch(required, *exceptions) ⇒ Object
57
58
59
60
61
62
63
64
65
|
# File 'lib/solid_use_case/either.rb', line 57
def catch(required, *exceptions)
exceptions << required
result = attempt_all do
try { yield }
end
if result.is_a?(Failure) && exceptions.any?
raise result.value unless exceptions.include?(result.value)
end
end
|
#check_each(array, continue_with: array) ⇒ Object
38
39
40
41
42
43
44
45
46
47
48
49
|
# File 'lib/solid_use_case/either.rb', line 38
def check_each(array, continue_with: array)
failure = nil
array.find do |item|
item_result = yield(item)
if item_result.is_a?(Failure)
failure = item_result
true
end
end
failure || continue(continue_with)
end
|
#check_exists(val, error = :not_found) ⇒ Object
Also known as:
maybe_continue
# # # # # Helpers # # # # # #
30
31
32
33
34
35
36
|
# File 'lib/solid_use_case/either.rb', line 30
def check_exists(val, error=:not_found)
if val.nil?
fail(error)
else
continue(val)
end
end
|
#fail(type, data = {}) ⇒ Object
67
68
69
70
|
# File 'lib/solid_use_case/either.rb', line 67
def fail(type, data={})
data[:type] = type
Failure(ErrorStruct.new(data))
end
|
#run(inputs) ⇒ Object
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
# File 'lib/solid_use_case/either.rb', line 4
def run(inputs)
steps = self.class.instance_variable_get("@__steps").clone
current_result = Success(inputs)
return current_result unless steps
while steps.count > 0
next_step = steps.shift
current_result = current_result.and_then do
if next_step.is_a?(Class) && (next_step.respond_to? :can_run_either?) && next_step.can_run_either?
next_step.run(current_result.value)
elsif next_step.is_a?(Symbol)
self.send(next_step, current_result.value)
else
raise "Invalid step type: #{next_step.inspect}"
end
end
end
current_result
end
|