forked from dry-rb/dry-monads
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathresult.rb
More file actions
463 lines (409 loc) · 12.4 KB
/
Copy pathresult.rb
File metadata and controls
463 lines (409 loc) · 12.4 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# frozen_string_literal: true
module Dry
module Monads
# Represents an operation which either succeeded or failed.
#
# @api public
class Result
include Transformer
include ConversionStubs[:to_maybe, :to_validated]
# @return [Object] Successful result
attr_reader :success
# @return [Object] Error
attr_reader :failure
class << self
# Wraps the given value with Success.
#
# @overload pure(value)
# @param value [Object]
# @return [Result::Success]
#
# @overload pure(&block)
# @param block [Proc] a block to be wrapped with Success
# @return [Result::Success]
#
def pure(value = Undefined, &block)
Success.new(Undefined.default(value, block))
end
end
# Returns self, added to keep the interface compatible with other monads.
#
# @return [Result::Success, Result::Failure]
def to_result = self
# Returns self.
#
# @return [Result::Success, Result::Failure]
def to_monad = self
# Returns the Result monad.
# This is how we're doing polymorphism in Ruby 😕
#
# @return [Monad]
def monad = Result
# Represents a value of a successful operation.
#
# @api public
class Success < Result
include RightBiased::Right
include ::Dry::Equalizer(:value!)
# Shortcut for Success([...])
#
# @example
# include Dry::Monads[:result]
#
# def call
# Success[200, {}, ['ok']] # => Success([200, {}, ['ok']])
# end
#
# @api public
def self.[](*value) = new(value)
alias_method :success, :value!
# @param value [Object] a value of a successful operation
def initialize(value)
super()
@value = value
end
# Apply the second function to value.
#
# @api public
def result(_, f) = f.(@value)
# Returns false
def failure? = false
# Returns true
def success? = true
# Does the same thing as #bind except it also wraps the value
# in an instance of Result::Success monad. This allows for easier
# chaining of calls.
#
# @example
# Dry::Monads.Success(4).fmap(&:succ).fmap(->(n) { n**2 }) # => Success(25)
#
# @param args [Array<Object>] arguments will be transparently passed through to #bind
# @return [Result::Success]
def fmap(...) = Success.new(bind(...))
# Returns result of applying first function to the internal value.
#
# @example
# Dry::Monads.Success(1).either(-> x { x + 1 }, -> x { x + 2 }) # => 2
#
# @param f [#call] Function to apply
# @param _ [#call] Ignored
# @return [Any] Return value of `f`
def either(f, _) = f.(success)
# @return [String]
def to_s
if Unit.equal?(@value)
"Success()"
else
"Success(#{@value.inspect})"
end
end
alias_method :inspect, :to_s
def pretty_print(pp)
pp.text "Success("
unless Unit.equal?(@value)
pp.group(1) do
pp.breakable("")
pp.pp(@value)
end
end
pp.text ")"
end
# Transforms to a Failure instance
#
# @return [Result::Failure]
def flip
Failure.new(@value, RightBiased::Left.trace_caller)
end
# Ignores values and returns self, see {Failure#alt_map}
#
# @return [Result::Success]
def alt_map(_ = nil, &) = self
end
# Represents a value of a failed operation.
#
# @api public
class Failure < Result
include RightBiased::Left
include ::Dry::Equalizer(:failure)
singleton_class.alias_method(:call, :new)
# Shortcut for Failure([...])
#
# @example
# include Dry::Monads[:result]
#
# def call
# Failure[:error, :not_found] # => Failure([:error, :not_found])
# end
#
# @api public
def self.[](*value)
new(value, RightBiased::Left.trace_caller)
end
# Returns a constructor proc
#
# @return [Proc]
def self.to_proc
@to_proc ||= method(:new).to_proc
end
# Line where the value was constructed
#
# @return [String]
# @api public
attr_reader :trace
# @param value [Object] failure value
# @param trace [String] caller line
def initialize(value, trace = RightBiased::Left.trace_caller)
super()
@value = value
@trace = trace
end
# @private
def failure = @value
# Apply the first function to value.
#
# @api public
def result(f, _) = f.(@value)
# Returns true
def failure? = true
# Returns false
def success? = false
# If a block is given passes internal value to it and returns the result,
# otherwise simply returns the first argument.
#
# @example
# Dry::Monads.Failure(ArgumentError.new('error message')).or(&:message)
# # => "error message"
#
# @param args [Array<Object>] arguments that will be passed to a block
# if one was given, otherwise the first
# value will be returned
# @return [Object]
def or(*args)
if block_given?
yield(@value, *args)
else
args[0]
end
end
# A lifted version of `#or`. Wraps the passed value or the block
# result with Result::Success.
#
# @example
# Dry::Monads.Failure.new('no value').or_fmap('value') # => Success("value")
# Dry::Monads.Failure.new('no value').or_fmap { 'value' } # => Success("value")
#
# @param args [Array<Object>] arguments will be passed to the underlying `#or` call
# @return [Result::Success] Wrapped value
def or_fmap(...) = Success.new(self.or(...))
# @return [String]
def to_s
if Unit.equal?(@value)
"Failure()"
else
"Failure(#{@value.inspect})"
end
end
alias_method :inspect, :to_s
def pretty_print(pp)
pp.text "Failure("
unless Unit.equal?(@value)
pp.group(1) do
pp.breakable("")
pp.pp(@value)
end
end
pp.text ")"
end
# Transform to a Success instance
#
# @return [Result::Success]
def flip = Success.new(@value)
# @see RightBiased::Left#value_or
def value_or(val = nil)
if block_given?
yield(@value)
else
val
end
end
# @param other [Result]
# @return [Boolean]
def ===(other)
Failure === other && failure === other.failure
end
# Returns result of applying second function to the internal value.
#
# @example
# Dry::Monads.Failure(1).either(-> x { x + 1 }, -> x { x + 2 }) # => 3
#
# @param _ [#call] Ignored
# @param g [#call] Function to call
# @return [Any] Return value of `g`
def either(_, g) = g.(failure)
# Lifts a block/proc over Failure
#
# @overload alt_map(proc)
# @param proc [#call]
# @return [Result::Failure]
#
# @overload alt_map
# @param block [Proc]
# @return [Result::Failure]
#
def alt_map(proc = Undefined, &block)
f = Undefined.default(proc, block)
self.class.new(f.(failure), RightBiased::Left.trace_caller)
end
end
# A module that can be included for easier access to Result monads.
#
# @api public
module Mixin
# @see Result::Success
Success = Result::Success
# @see Result::Failure
Failure = Result::Failure
# Value constructors
#
module Constructors
# Success constructor
#
# @overload Success(value)
# @param value [Object]
# @return [Result::Success]
#
# @overload Success(&block)
# @param block [Proc] a block to be wrapped with Success
# @return [Result::Success]
#
def Success(value = Undefined, &block)
v = Undefined.default(value, block || Unit)
Success.new(v)
end
# Failure constructor
#
# @overload Success(value)
# @param value [Object]
# @return [Result::Failure]
#
# @overload Success(&block)
# @param block [Proc] a block to be wrapped with Failure
# @return [Result::Failure]
#
def Failure(value = Undefined, &block)
v = Undefined.default(value, block || Unit)
Failure.new(v, RightBiased::Left.trace_caller)
end
end
include Constructors
end
end
extend Result::Mixin::Constructors
# @see Result::Success
Success = Result::Success
# @see Result::Failure
Failure = Result::Failure
# Creates a module that has two methods: `Success` and `Failure`.
# `Success` is identical to {Result::Mixin::Constructors#Success} and Failure
# rejects values that don't conform the value of the `error`
# parameter. This is essentially a Result type with the `Failure` part
# fixed.
#
# @example using dry-types
# module Types
# include Dry::Types.module
# end
#
# class Operation
# # :user_not_found and :account_not_found are the only
# # values allowed as failure results
# Error =
# Types.Value(:user_not_found) |
# Types.Value(:account_not_found)
#
# include Dry::Monads::Result(Error)
#
# def find_account(id)
# account = acount_repo.find(id)
#
# account ? Success(account) : Failure(:account_not_found)
# end
#
# def find_user(id)
# # ...
# end
# end
#
# @param error [#===] the type of allowed failures
# @return [Module]
def self.Result(error, **options)
Result::Fixed[error, **options]
end
class Maybe
class Some < Maybe
# Converts to Sucess(value!)
#
# @param fail [#call] Fallback value
# @param block [Proc] Fallback block
# @return [Success<Any>]
def to_result(_fail = Unit, &) = Result::Success.new(@value)
end
class None < Maybe
# Converts to Failure(fallback_value)
#
# @param fail [#call] Fallback value
# @param block [Proc] Fallback block
# @return [Failure<Any>]
def to_result(fail = Unit)
if block_given?
Result::Failure.new(yield)
else
Result::Failure.new(fail)
end
end
end
end
class Task
# Converts to Result. Blocks the current thread if required.
#
# @return [Result]
def to_result
if promise.wait.fulfilled?
Result::Success.new(promise.value)
else
Result::Failure.new(promise.reason, RightBiased::Left.trace_caller)
end
end
end
class Try
class Value < Try
# @return [Result::Success]
def to_result = ::Dry::Monads::Result::Success.new(@value)
end
class Error < Try
# @return [Result::Failure]
def to_result
Result::Failure.new(exception, RightBiased::Left.trace_caller)
end
end
end
class Validated
class Valid < Validated
# Converts to Result::Success
#
# @return [Result::Success]
def to_result = Result.pure(value!)
end
class Invalid < Validated
# Converts to Result::Failure
#
# @return [Result::Failure]
def to_result
Result::Failure.new(error, RightBiased::Left.trace_caller)
end
end
end
require "dry/monads/registry"
register_mixin(:result, Result::Mixin)
end
end