bcdd-result 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.rubocop.yml +22 -0
- data/.rubocop_todo.yml +19 -0
- data/CHANGELOG.md +43 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/LICENSE.txt +21 -0
- data/README.md +371 -0
- data/Rakefile +16 -0
- data/Steepfile +31 -0
- data/lib/bcdd/result/error.rb +24 -0
- data/lib/bcdd/result/failure.rb +23 -0
- data/lib/bcdd/result/success.rb +23 -0
- data/lib/bcdd/result/version.rb +7 -0
- data/lib/bcdd/result.rb +78 -0
- data/sig/bcdd/result.rbs +66 -0
- metadata +63 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: e27dee9c053eeb9f6025b17e09eede49ca6cbc69cd9120947bad34b26a79859d
|
4
|
+
data.tar.gz: c8c080d43a3eb46139f7bf5299c64346809d1c0df4bf0181ccb02ba3005d5ee0
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 253e14ef154c2b863bb65139134a903b2a6fd035fb7a995158cf5ebab395d6ba2bd9f8e999c29305f2d2cd2f6e10db9923166a13d1f06e627df276c87c7a644d
|
7
|
+
data.tar.gz: 7d62559447a5ee3cb665713645f1db7729428f9cf94bd349574758ea3f9bae361f65a218640b2d5bfeb138ef108c27dec426a44ec89dbc971620671b6eab945c
|
data/.rubocop.yml
ADDED
@@ -0,0 +1,22 @@
|
|
1
|
+
inherit_from: .rubocop_todo.yml
|
2
|
+
|
3
|
+
require:
|
4
|
+
- rubocop-performance
|
5
|
+
- rubocop-minitest
|
6
|
+
- rubocop-rake
|
7
|
+
|
8
|
+
AllCops:
|
9
|
+
NewCops: enable
|
10
|
+
TargetRubyVersion: 2.7
|
11
|
+
|
12
|
+
Layout/LineLength:
|
13
|
+
Max: 120
|
14
|
+
|
15
|
+
Layout/ExtraSpacing:
|
16
|
+
AllowBeforeTrailingComments: true
|
17
|
+
|
18
|
+
Style/ClassAndModuleChildren:
|
19
|
+
Enabled: false
|
20
|
+
|
21
|
+
Minitest/MultipleAssertions:
|
22
|
+
Enabled: false
|
data/.rubocop_todo.yml
ADDED
@@ -0,0 +1,19 @@
|
|
1
|
+
# This configuration was generated by
|
2
|
+
# `rubocop --auto-gen-config`
|
3
|
+
# on 2023-09-23 03:05:24 UTC using RuboCop version 1.56.3.
|
4
|
+
# The point is for the user to remove these configuration records
|
5
|
+
# one by one as the offenses are removed from the code base.
|
6
|
+
# Note that changes in the inspected code, or installation of new
|
7
|
+
# versions of RuboCop, may require this file to be generated again.
|
8
|
+
|
9
|
+
# Offense count: 8
|
10
|
+
# Configuration parameters: AllowedConstants.
|
11
|
+
Style/Documentation:
|
12
|
+
Exclude:
|
13
|
+
- 'spec/**/*'
|
14
|
+
- 'test/**/*'
|
15
|
+
- 'lib/bcdd/result.rb'
|
16
|
+
- 'lib/bcdd/result/base.rb'
|
17
|
+
- 'lib/bcdd/result/error.rb'
|
18
|
+
- 'lib/bcdd/result/failure.rb'
|
19
|
+
- 'lib/bcdd/result/success.rb'
|
data/CHANGELOG.md
ADDED
@@ -0,0 +1,43 @@
|
|
1
|
+
## [Unreleased]
|
2
|
+
|
3
|
+
## [0.1.0] - 2023-09-25
|
4
|
+
|
5
|
+
### Added
|
6
|
+
|
7
|
+
- Add `BCDD::Result` to represent a result.
|
8
|
+
|
9
|
+
- Add `BCDD::Result#type` to get the result type. The type must be a symbol.
|
10
|
+
|
11
|
+
- Add `BCDD::Result#value` to get the result value. The value can be anything.
|
12
|
+
|
13
|
+
- Add `BCDD::Result#success?` to check if the result is a success. You can also check the result type by passing an argument to it. For example, `result.success?(:ok)` will check if the result is a success and if the type is `:ok`.
|
14
|
+
|
15
|
+
- Add `BCDD::Result#failure?` to check if the result is a failure. You can also check the result type by passing an argument to it. For example, `result.failure?(:error)` will check if the result is a failure and if the type is `:error`.
|
16
|
+
|
17
|
+
- Add `BCDD::Result#value_or` to get the value of a successful result or a default value (from the block) if it is a failure.
|
18
|
+
|
19
|
+
- Add `BCDD::Result#==` to compare two results.
|
20
|
+
|
21
|
+
- Add `BCDD::Result#eql?` to compare two results.
|
22
|
+
|
23
|
+
- Add `BCDD::Result#hash` to get the hash of a result.
|
24
|
+
|
25
|
+
- Add `BCDD::Result#inspect` to get the string representation of a result.
|
26
|
+
|
27
|
+
- Add `BCDD::Result#on` to execute a block depending on the result type (independently of the result being a success or a failure). The block will receive the result value as an argument, and the result itself will be returned after (or not) the block execution. The method can be called multiple times and with one or more arguments. For example, `result.on(:ok, :error) { |value| # ... }` will execute the block if the result type is `:ok` or `:error`.
|
28
|
+
|
29
|
+
- Add `BCDD::Result#on_success` to execute a block if the result is a success. It works like `BCDD::Result#on` but only for success results.
|
30
|
+
|
31
|
+
- Add `BCDD::Result#on_failure` to execute a block if the result is a failure. It works like `BCDD::Result#on` but only for failure results.
|
32
|
+
|
33
|
+
- Add `BCDD::Result#and_then` to execute the block if the result is a success. You can use it to chain multiple operations. If the block returns a failure result and there are other `and_then` calls after it, the next blocks will be skipped.
|
34
|
+
|
35
|
+
- Add `BCDD::Result#data` as an alias for `BCDD::Result#value`.
|
36
|
+
|
37
|
+
- Add `BCDD::Result#data_or` as an alias for `BCDD::Result#value_or`.
|
38
|
+
|
39
|
+
- Add `BCDD::Result#on_type` as an alias for `BCDD::Result#on`.
|
40
|
+
|
41
|
+
- Add `BCDD::Result::Success()` to factory a success result.
|
42
|
+
|
43
|
+
- Add `BCDD::Result::Failure()` to factory a failure result.
|
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,84 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
6
|
+
|
7
|
+
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
8
|
+
|
9
|
+
## Our Standards
|
10
|
+
|
11
|
+
Examples of behavior that contributes to a positive environment for our community include:
|
12
|
+
|
13
|
+
* Demonstrating empathy and kindness toward other people
|
14
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
15
|
+
* Giving and gracefully accepting constructive feedback
|
16
|
+
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
17
|
+
* Focusing on what is best not just for us as individuals, but for the overall community
|
18
|
+
|
19
|
+
Examples of unacceptable behavior include:
|
20
|
+
|
21
|
+
* The use of sexualized language or imagery, and sexual attention or
|
22
|
+
advances of any kind
|
23
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
24
|
+
* Public or private harassment
|
25
|
+
* Publishing others' private information, such as a physical or email
|
26
|
+
address, without their explicit permission
|
27
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
28
|
+
professional setting
|
29
|
+
|
30
|
+
## Enforcement Responsibilities
|
31
|
+
|
32
|
+
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
33
|
+
|
34
|
+
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
35
|
+
|
36
|
+
## Scope
|
37
|
+
|
38
|
+
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
39
|
+
|
40
|
+
## Enforcement
|
41
|
+
|
42
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at rodrigo.serradura@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
|
43
|
+
|
44
|
+
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
45
|
+
|
46
|
+
## Enforcement Guidelines
|
47
|
+
|
48
|
+
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
49
|
+
|
50
|
+
### 1. Correction
|
51
|
+
|
52
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
53
|
+
|
54
|
+
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
55
|
+
|
56
|
+
### 2. Warning
|
57
|
+
|
58
|
+
**Community Impact**: A violation through a single incident or series of actions.
|
59
|
+
|
60
|
+
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
61
|
+
|
62
|
+
### 3. Temporary Ban
|
63
|
+
|
64
|
+
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
65
|
+
|
66
|
+
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
67
|
+
|
68
|
+
### 4. Permanent Ban
|
69
|
+
|
70
|
+
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
71
|
+
|
72
|
+
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
73
|
+
|
74
|
+
## Attribution
|
75
|
+
|
76
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
|
77
|
+
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
78
|
+
|
79
|
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
|
80
|
+
|
81
|
+
[homepage]: https://www.contributor-covenant.org
|
82
|
+
|
83
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
84
|
+
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2023 Rodrigo Serradura
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,371 @@
|
|
1
|
+
# BCDD::Result <!-- omit in toc -->
|
2
|
+
|
3
|
+
A general-purpose result monad that allows you to create objects that represent a success (`BCDD::Result::Success`) or failure (`BCDD::Result::Failure`).
|
4
|
+
|
5
|
+
**What problem does it solve?**
|
6
|
+
|
7
|
+
It allows you to consistently represent the concept of success and failure throughout your codebase.
|
8
|
+
|
9
|
+
Furthermore, this abstraction exposes several methods that will be useful to make the code flow react clearly and cleanly to the result represented by these objects.
|
10
|
+
|
11
|
+
- [Installation](#installation)
|
12
|
+
- [Usage](#usage)
|
13
|
+
- [Reference](#reference)
|
14
|
+
- [Result Attributes](#result-attributes)
|
15
|
+
- [Receiving types in `result.success?` or `result.failure?`](#receiving-types-in-resultsuccess-or-resultfailure)
|
16
|
+
- [Result Hooks](#result-hooks)
|
17
|
+
- [`result.on`](#resulton)
|
18
|
+
- [`result.on_type`](#resulton_type)
|
19
|
+
- [`result.on_success`](#resulton_success)
|
20
|
+
- [`result.on_failure`](#resulton_failure)
|
21
|
+
- [Result value](#result-value)
|
22
|
+
- [`result.value_or`](#resultvalue_or)
|
23
|
+
- [`result.data_or`](#resultdata_or)
|
24
|
+
- [Railway Oriented Programming](#railway-oriented-programming)
|
25
|
+
- [`result.and_then`](#resultand_then)
|
26
|
+
- [About](#about)
|
27
|
+
- [Development](#development)
|
28
|
+
- [Contributing](#contributing)
|
29
|
+
- [License](#license)
|
30
|
+
- [Code of Conduct](#code-of-conduct)
|
31
|
+
|
32
|
+
|
33
|
+
## Installation
|
34
|
+
|
35
|
+
Install the gem and add to the application's Gemfile by executing:
|
36
|
+
|
37
|
+
$ bundle add bcdd-result
|
38
|
+
|
39
|
+
If bundler is not being used to manage dependencies, install the gem by executing:
|
40
|
+
|
41
|
+
$ gem install bcdd-result
|
42
|
+
|
43
|
+
## Usage
|
44
|
+
|
45
|
+
To create a result, you must define a type (symbol) and its value (any kind of object). e.g.,
|
46
|
+
|
47
|
+
```ruby
|
48
|
+
BCDD::Result::Success(:ok, :1) #
|
49
|
+
# The value can be any kind of object
|
50
|
+
BCDD::Result::Failure(:err, 'the value') #
|
51
|
+
```
|
52
|
+
|
53
|
+
The reason for defining a `type` is that it is very common for a method/operation to return different types of successes or failures. Because of this, the `type` will always be required. e,g.,
|
54
|
+
|
55
|
+
```ruby
|
56
|
+
BCDD::Result::Success(:ok) #
|
57
|
+
# The type is mandatory and the value is optional
|
58
|
+
BCDD::Result::Failure(:err) #
|
59
|
+
```
|
60
|
+
|
61
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
62
|
+
|
63
|
+
## Reference
|
64
|
+
|
65
|
+
### Result Attributes
|
66
|
+
|
67
|
+
Both `BCDD::Result::Success` and `BCDD::Result::Failure` are composed of the same methods. Look at the basic ones:
|
68
|
+
|
69
|
+
**BCDD::Result::Success**
|
70
|
+
|
71
|
+
```ruby
|
72
|
+
################
|
73
|
+
# With a value #
|
74
|
+
################
|
75
|
+
result = BCDD::Result::Success(:ok, my: 'value')
|
76
|
+
|
77
|
+
result.success? # true
|
78
|
+
result.failure? # false
|
79
|
+
result.type # :ok
|
80
|
+
result.value # {:my => "value"}
|
81
|
+
|
82
|
+
###################
|
83
|
+
# Without a value #
|
84
|
+
###################
|
85
|
+
result = BCDD::Result::Success(:yes)
|
86
|
+
|
87
|
+
result.success? # true
|
88
|
+
result.failure? # false
|
89
|
+
result.type # :yes
|
90
|
+
result.value # nil
|
91
|
+
```
|
92
|
+
|
93
|
+
**BCDD::Result::Failure**
|
94
|
+
|
95
|
+
```ruby
|
96
|
+
################
|
97
|
+
# With a value #
|
98
|
+
################
|
99
|
+
result = BCDD::Result::Failure(:err, my: 'value')
|
100
|
+
|
101
|
+
result.success? # false
|
102
|
+
result.failure? # true
|
103
|
+
result.type # :err
|
104
|
+
result.value # {:my => "value"}
|
105
|
+
|
106
|
+
###################
|
107
|
+
# Without a value #
|
108
|
+
###################
|
109
|
+
result = BCDD::Result::Failure(:no)
|
110
|
+
|
111
|
+
result.success? # false
|
112
|
+
result.failure? # true
|
113
|
+
result.type # :no
|
114
|
+
result.value # nil
|
115
|
+
```
|
116
|
+
|
117
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
118
|
+
|
119
|
+
#### Receiving types in `result.success?` or `result.failure?`
|
120
|
+
|
121
|
+
`BCDD::Result#success?` and `BCDD::Result#failure?` are methods that allow you to check if the result is a success or a failure.
|
122
|
+
|
123
|
+
You can also check the result type by passing an argument to it. For example, `result.success?(:ok)` will check if the result is a success and if the type is `:ok`.
|
124
|
+
|
125
|
+
```ruby
|
126
|
+
result = BCDD::Result::Success(:ok)
|
127
|
+
|
128
|
+
result.success? # true
|
129
|
+
result.success?(:ok) # true
|
130
|
+
result.success?(:okay) # false
|
131
|
+
```
|
132
|
+
|
133
|
+
The same is valid for `BCDD::Result#failure?`.
|
134
|
+
|
135
|
+
```ruby
|
136
|
+
result = BCDD::Result::Failure(:err)
|
137
|
+
|
138
|
+
result.failure? # true
|
139
|
+
result.failure?(:err) # true
|
140
|
+
result.failure?(:error) # false
|
141
|
+
```
|
142
|
+
|
143
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
144
|
+
|
145
|
+
### Result Hooks
|
146
|
+
|
147
|
+
Result hooks are methods that allow you to perform a block of code depending on the result type.
|
148
|
+
|
149
|
+
To exemplify the them, I will implement a method that knows how to divide two numbers.
|
150
|
+
|
151
|
+
```ruby
|
152
|
+
def divide(arg1, arg2)
|
153
|
+
arg1.is_a?(::Numeric) or return BCDD::Result::Failure(:invalid_arg, 'arg1 must be numeric')
|
154
|
+
arg2.is_a?(::Numeric) or return BCDD::Result::Failure(:invalid_arg, 'arg2 must be numeric')
|
155
|
+
|
156
|
+
return BCDD::Result::Failure(:division_by_zero, 'arg2 must not be zero') if arg2.zero?
|
157
|
+
|
158
|
+
BCDD::Result::Success(:division_completed, arg1 / arg2)
|
159
|
+
end
|
160
|
+
```
|
161
|
+
|
162
|
+
#### `result.on`
|
163
|
+
|
164
|
+
`BCDD::Result#on` will perform the block when the type matches the result type.
|
165
|
+
|
166
|
+
Regardless of the block being executed, the return of the method will always be the result itself.
|
167
|
+
|
168
|
+
The result value will be exposed as the first argument of the block.
|
169
|
+
|
170
|
+
```ruby
|
171
|
+
result = divide(nil, 2)
|
172
|
+
|
173
|
+
output =
|
174
|
+
result
|
175
|
+
.on(:invalid_arg) { |msg| puts msg }
|
176
|
+
.on(:division_by_zero) { |msg| puts msg }
|
177
|
+
.on(:division_completed) { |number| puts number }
|
178
|
+
|
179
|
+
# The code above will print 'arg1 must be numeric' and return the result itself.
|
180
|
+
|
181
|
+
result.object_id == output.object_id # true
|
182
|
+
```
|
183
|
+
|
184
|
+
You can define multiple types to be handled by the same hook/block
|
185
|
+
```ruby
|
186
|
+
result = divide(4, 0)
|
187
|
+
|
188
|
+
output =
|
189
|
+
result.on(:invalid_arg, :division_by_zero, :division_completed) { |value| puts value }
|
190
|
+
|
191
|
+
# The code above will print 'arg2 must not be zero' and return the result itself.
|
192
|
+
|
193
|
+
result.object_id == output.object_id # true
|
194
|
+
```
|
195
|
+
|
196
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
197
|
+
|
198
|
+
#### `result.on_type`
|
199
|
+
|
200
|
+
`BCDD::Result#on_type` is an alias of `BCDD::Result#on`.
|
201
|
+
|
202
|
+
#### `result.on_success`
|
203
|
+
|
204
|
+
`BCDD::Result#on_success` is very similar to the `BCDD::Result#on` hook. The main differences are:
|
205
|
+
|
206
|
+
1. Only perform the block when the result is a success.
|
207
|
+
2. If the type is missing it will perform the block for any success.
|
208
|
+
|
209
|
+
```ruby
|
210
|
+
# It performs the block and return itself.
|
211
|
+
|
212
|
+
divide(4, 2).on_success { |number| puts number }
|
213
|
+
|
214
|
+
divide(4, 2).on_success(:division_completed) { |number| puts number }
|
215
|
+
|
216
|
+
# It doesn't perform the block, but return itself.
|
217
|
+
|
218
|
+
divide(4, 4).on_success(:ok) { |value| puts value }
|
219
|
+
|
220
|
+
divide(4, 4).on_failure { |error| puts error }
|
221
|
+
```
|
222
|
+
|
223
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
224
|
+
|
225
|
+
#### `result.on_failure`
|
226
|
+
|
227
|
+
Is the opposite of `Result#on_success`.
|
228
|
+
|
229
|
+
```ruby
|
230
|
+
# It performs the block and return itself.
|
231
|
+
|
232
|
+
divide(nil, 2).on_failure { |error| puts error }
|
233
|
+
|
234
|
+
divide(4, 0).on_failure(:invalid_arg, :division_by_zero) { |error| puts error }
|
235
|
+
|
236
|
+
# It doesn't perform the block, but return itself.
|
237
|
+
|
238
|
+
divide(4, 0).on_success { |number| puts number }
|
239
|
+
|
240
|
+
divide(4, 0).on_failure(:invalid_arg) { |error| puts error }
|
241
|
+
```
|
242
|
+
|
243
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
244
|
+
|
245
|
+
### Result value
|
246
|
+
|
247
|
+
The most simple way to get the result value is by calling `BCDD::Result#value` or `BCDD::Result#data`.
|
248
|
+
|
249
|
+
But sometimes you need to get the value of a successful result or a default value if it is a failure. In this case, you can use `BCDD::Result#value_or` or `BCDD::Result#data_or`.
|
250
|
+
|
251
|
+
#### `result.value_or`
|
252
|
+
|
253
|
+
`BCCD::Result#value_or` returns the value when the result is a success, but if is a failure the block will be performed, and its outcome will be the output.
|
254
|
+
|
255
|
+
```ruby
|
256
|
+
def divide(arg1, arg2)
|
257
|
+
arg1.is_a?(::Numeric) or return BCDD::Result::Failure(:invalid_arg)
|
258
|
+
arg2.is_a?(::Numeric) or return BCDD::Result::Failure(:invalid_arg)
|
259
|
+
|
260
|
+
return BCDD::Result::Failure(:division_by_zero) if arg2.zero?
|
261
|
+
|
262
|
+
BCDD::Result::Success(:division_completed, arg1 / arg2)
|
263
|
+
end
|
264
|
+
|
265
|
+
# When the result is success
|
266
|
+
divide(4, 2).value_or { 0 } # 2
|
267
|
+
|
268
|
+
# When the result is failure
|
269
|
+
divide('4', 2).value_or { 0 } # 0
|
270
|
+
divide(4, '2').value_or { 0 } # 0
|
271
|
+
divide(100, 0).value_or { 0 } # 0
|
272
|
+
```
|
273
|
+
|
274
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
275
|
+
|
276
|
+
#### `result.data_or`
|
277
|
+
|
278
|
+
`BCDD::Result#data_or` is an alias of `BCDD::Result#value_or`.
|
279
|
+
|
280
|
+
|
281
|
+
### Railway Oriented Programming
|
282
|
+
|
283
|
+
#### `result.and_then`
|
284
|
+
|
285
|
+
This feature/pattern is also known as ["Railway Oriented Programming"](https://fsharpforfunandprofit.com/rop/).
|
286
|
+
|
287
|
+
The idea is to chain blocks and creates a pipeline of operations that can be interrupted by a failure.
|
288
|
+
|
289
|
+
In other words, the block will be executed only if the result is a success.
|
290
|
+
So, if some block returns a failure, the following blocks will be skipped.
|
291
|
+
|
292
|
+
Due to this characteristic, you can use this feature to express some logic as a sequence of operations. And have the guarantee that the process will stop by the first failure detection, and if everything is ok, the final result will be a success. e.g.,
|
293
|
+
|
294
|
+
```ruby
|
295
|
+
module Divide
|
296
|
+
extend self
|
297
|
+
|
298
|
+
def call(arg1, arg2)
|
299
|
+
validate_numbers(arg1, arg2)
|
300
|
+
.and_then { |numbers| validate_non_zero(numbers) }
|
301
|
+
.and_then { |numbers| divide(numbers) }
|
302
|
+
end
|
303
|
+
|
304
|
+
private
|
305
|
+
|
306
|
+
def validate_numbers(arg1, arg2)
|
307
|
+
arg1.is_a?(::Numeric) or return BCDD::Result::Failure(:invalid_arg, 'arg1 must be numeric')
|
308
|
+
arg2.is_a?(::Numeric) or return BCDD::Result::Failure(:invalid_arg, 'arg2 must be numeric')
|
309
|
+
|
310
|
+
BCDD::Result::Success(:ok, [arg1, arg2])
|
311
|
+
end
|
312
|
+
|
313
|
+
def validate_non_zero(numbers)
|
314
|
+
return BCDD::Result::Success(:ok, numbers) unless numbers.last.zero?
|
315
|
+
|
316
|
+
BCDD::Result::Failure(:division_by_zero, "arg2 must not be zero")
|
317
|
+
end
|
318
|
+
|
319
|
+
def divide((number1, number2))
|
320
|
+
BCDD::Result::Success(:division_completed, number1 / number2)
|
321
|
+
end
|
322
|
+
end
|
323
|
+
```
|
324
|
+
|
325
|
+
Example of outputs:
|
326
|
+
|
327
|
+
```ruby
|
328
|
+
Divide.call('4', 2)
|
329
|
+
#<BCDD::Result::Failure type=:invalid_arg data="arg1 must be numeric">
|
330
|
+
|
331
|
+
Divide.call(2, '2')
|
332
|
+
#<BCDD::Result::Failure type=:invalid_arg data="arg2 must be numeric">
|
333
|
+
|
334
|
+
Divide.call(2, 0)
|
335
|
+
#<BCDD::Result::Failure type=:division_by_zero data="arg2 must not be zero">
|
336
|
+
|
337
|
+
Divide.call(2, 2)
|
338
|
+
#<BCDD::Result::Success type=:division_completed data=1>
|
339
|
+
```
|
340
|
+
|
341
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
342
|
+
|
343
|
+
## About
|
344
|
+
|
345
|
+
[Rodrigo Serradura](https://github.com/serradura) created this project. He is the B/CDD process/method creator and has already made similar gems like the [u-case](https://github.com/serradura/u-case) and [kind](https://github.com/serradura/kind/blob/main/lib/kind/result.rb). This gem is a general-purpose abstraction/monad, but it also contains key features that serve as facilitators for adopting B/CDD in the code.
|
346
|
+
|
347
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
348
|
+
|
349
|
+
## Development
|
350
|
+
|
351
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rake` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
352
|
+
|
353
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
354
|
+
|
355
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
356
|
+
|
357
|
+
## Contributing
|
358
|
+
|
359
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/B-CDD/bcdd-result. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/B-CDD/bcdd-result/blob/master/CODE_OF_CONDUCT.md).
|
360
|
+
|
361
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
362
|
+
|
363
|
+
## License
|
364
|
+
|
365
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
366
|
+
|
367
|
+
<p align="right">(<a href="#bcddresult-">⬆️ back to top</a>)</p>
|
368
|
+
|
369
|
+
## Code of Conduct
|
370
|
+
|
371
|
+
Everyone interacting in the BCDD::Result project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/B-CDD/bcdd-result/blob/master/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
@@ -0,0 +1,16 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'bundler/gem_tasks'
|
4
|
+
require 'rake/testtask'
|
5
|
+
|
6
|
+
Rake::TestTask.new(:test) do |t|
|
7
|
+
t.libs << 'test'
|
8
|
+
t.libs << 'lib'
|
9
|
+
t.test_files = FileList['test/**/*_test.rb']
|
10
|
+
end
|
11
|
+
|
12
|
+
require 'rubocop/rake_task'
|
13
|
+
|
14
|
+
RuboCop::RakeTask.new
|
15
|
+
|
16
|
+
task default: %i[test rubocop]
|
data/Steepfile
ADDED
@@ -0,0 +1,31 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
D = Steep::Diagnostic
|
4
|
+
|
5
|
+
target :lib do
|
6
|
+
signature 'sig'
|
7
|
+
|
8
|
+
check 'lib' # Directory name
|
9
|
+
# check 'Gemfile' # File name
|
10
|
+
# check 'app/models/**/*.rb' # Glob
|
11
|
+
# ignore 'lib/templates/*.rb'
|
12
|
+
|
13
|
+
# library 'pathname' # Standard libraries
|
14
|
+
# library 'strong_json' # Gems
|
15
|
+
|
16
|
+
# configure_code_diagnostics(D::Ruby.default) # `default` diagnostics setting (applies by default)
|
17
|
+
# configure_code_diagnostics(D::Ruby.strict) # `strict` diagnostics setting
|
18
|
+
# configure_code_diagnostics(D::Ruby.lenient) # `lenient` diagnostics setting
|
19
|
+
# configure_code_diagnostics(D::Ruby.silent) # `silent` diagnostics setting
|
20
|
+
# configure_code_diagnostics do |hash| # You can setup everything yourself
|
21
|
+
# hash[D::Ruby::NoMethod] = :information
|
22
|
+
# end
|
23
|
+
end
|
24
|
+
|
25
|
+
# target :test do
|
26
|
+
# signature 'sig', 'sig-private'
|
27
|
+
#
|
28
|
+
# check 'test'
|
29
|
+
#
|
30
|
+
# # library 'pathname' # Standard libraries
|
31
|
+
# end
|
@@ -0,0 +1,24 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
class BCDD::Result
|
4
|
+
class Error < ::StandardError
|
5
|
+
class NotImplemented < self
|
6
|
+
end
|
7
|
+
|
8
|
+
class MissingTypeArgument < self
|
9
|
+
def initialize(_arg = nil)
|
10
|
+
super('A type (argument) is required to invoke the #on/#on_type method')
|
11
|
+
end
|
12
|
+
end
|
13
|
+
|
14
|
+
class UnexpectedBlockOutcome < self
|
15
|
+
def initialize(arg = nil)
|
16
|
+
message =
|
17
|
+
"Unexpected outcome: #{arg.inspect}. The block must return this object wrapped by " \
|
18
|
+
'BCDD::Result::Success or BCDD::Result::Failure'
|
19
|
+
|
20
|
+
super(message)
|
21
|
+
end
|
22
|
+
end
|
23
|
+
end
|
24
|
+
end
|
@@ -0,0 +1,23 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
class BCDD::Result
|
4
|
+
class Failure < self
|
5
|
+
def success?(_type = nil)
|
6
|
+
false
|
7
|
+
end
|
8
|
+
|
9
|
+
def failure?(type = nil)
|
10
|
+
type.nil? || type == self.type
|
11
|
+
end
|
12
|
+
|
13
|
+
def value_or
|
14
|
+
yield
|
15
|
+
end
|
16
|
+
|
17
|
+
alias data_or value_or
|
18
|
+
end
|
19
|
+
|
20
|
+
def self.Failure(type, value = nil)
|
21
|
+
Failure.new(type: type, value: value)
|
22
|
+
end
|
23
|
+
end
|
@@ -0,0 +1,23 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
class BCDD::Result
|
4
|
+
class Success < self
|
5
|
+
def success?(type = nil)
|
6
|
+
type.nil? || type == self.type
|
7
|
+
end
|
8
|
+
|
9
|
+
def failure?(_type = nil)
|
10
|
+
false
|
11
|
+
end
|
12
|
+
|
13
|
+
def value_or
|
14
|
+
value
|
15
|
+
end
|
16
|
+
|
17
|
+
alias data_or value_or
|
18
|
+
end
|
19
|
+
|
20
|
+
def self.Success(type, value = nil)
|
21
|
+
Success.new(type: type, value: value)
|
22
|
+
end
|
23
|
+
end
|
data/lib/bcdd/result.rb
ADDED
@@ -0,0 +1,78 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative 'result/version'
|
4
|
+
require_relative 'result/error'
|
5
|
+
require_relative 'result/failure'
|
6
|
+
require_relative 'result/success'
|
7
|
+
|
8
|
+
class BCDD::Result
|
9
|
+
attr_reader :type, :value
|
10
|
+
|
11
|
+
def initialize(type:, value:)
|
12
|
+
@type = type.to_sym
|
13
|
+
@value = value
|
14
|
+
end
|
15
|
+
|
16
|
+
def success?(_type = nil)
|
17
|
+
raise Error::NotImplemented
|
18
|
+
end
|
19
|
+
|
20
|
+
def failure?(_type = nil)
|
21
|
+
raise Error::NotImplemented
|
22
|
+
end
|
23
|
+
|
24
|
+
def value_or(&_block)
|
25
|
+
raise Error::NotImplemented
|
26
|
+
end
|
27
|
+
|
28
|
+
def ==(other)
|
29
|
+
self.class == other.class && type == other.type && value == other.value
|
30
|
+
end
|
31
|
+
alias eql? ==
|
32
|
+
|
33
|
+
def hash
|
34
|
+
[self.class, type, value].hash
|
35
|
+
end
|
36
|
+
|
37
|
+
def inspect
|
38
|
+
format('#<%<class_name>s type=%<type>p value=%<value>p>', class_name: self.class.name, type: type, value: value)
|
39
|
+
end
|
40
|
+
|
41
|
+
def on(*types)
|
42
|
+
raise Error::MissingTypeArgument if types.empty?
|
43
|
+
|
44
|
+
tap { yield(value, type) if expected_type?(types) }
|
45
|
+
end
|
46
|
+
|
47
|
+
def on_success(*types)
|
48
|
+
tap { yield(value, type) if success? && allowed_to_handle?(types) }
|
49
|
+
end
|
50
|
+
|
51
|
+
def on_failure(*types)
|
52
|
+
tap { yield(value, type) if failure? && allowed_to_handle?(types) }
|
53
|
+
end
|
54
|
+
|
55
|
+
def and_then
|
56
|
+
return self if failure?
|
57
|
+
|
58
|
+
result = yield(value)
|
59
|
+
|
60
|
+
return result if result.is_a?(::BCDD::Result)
|
61
|
+
|
62
|
+
raise Error::UnexpectedBlockOutcome, result
|
63
|
+
end
|
64
|
+
|
65
|
+
alias data value
|
66
|
+
alias data_or value_or
|
67
|
+
alias on_type on
|
68
|
+
|
69
|
+
private
|
70
|
+
|
71
|
+
def expected_type?(types)
|
72
|
+
types.any?(type)
|
73
|
+
end
|
74
|
+
|
75
|
+
def allowed_to_handle?(types)
|
76
|
+
types.empty? || expected_type?(types)
|
77
|
+
end
|
78
|
+
end
|
data/sig/bcdd/result.rbs
ADDED
@@ -0,0 +1,66 @@
|
|
1
|
+
module BCDD
|
2
|
+
class Result
|
3
|
+
VERSION: String
|
4
|
+
end
|
5
|
+
end
|
6
|
+
|
7
|
+
class BCDD::Result
|
8
|
+
attr_reader type: Symbol
|
9
|
+
attr_reader value: untyped
|
10
|
+
|
11
|
+
def initialize: (type: Symbol, value: untyped) -> void
|
12
|
+
|
13
|
+
def success?: (?Symbol type) -> bool
|
14
|
+
def failure?: (?Symbol type) -> bool
|
15
|
+
|
16
|
+
def value_or: { () -> untyped } -> untyped
|
17
|
+
|
18
|
+
def ==: (untyped) -> bool
|
19
|
+
alias eql? ==
|
20
|
+
|
21
|
+
def hash: -> Integer
|
22
|
+
|
23
|
+
def inspect: -> String
|
24
|
+
|
25
|
+
def on: (*Symbol) { (untyped, Symbol) -> void } -> BCDD::Result
|
26
|
+
def on_success: (*Symbol) { (untyped, Symbol) -> void } -> BCDD::Result
|
27
|
+
def on_failure: (*Symbol) { (untyped, Symbol) -> void } -> BCDD::Result
|
28
|
+
|
29
|
+
def and_then: { (untyped) -> untyped } -> BCDD::Result
|
30
|
+
|
31
|
+
alias data value
|
32
|
+
alias data_or value_or
|
33
|
+
alias on_type on
|
34
|
+
|
35
|
+
private
|
36
|
+
|
37
|
+
def expected_type?: (Array[Symbol]) -> bool
|
38
|
+
def allowed_to_handle?: (Array[Symbol]) -> bool
|
39
|
+
end
|
40
|
+
|
41
|
+
class BCDD::Result
|
42
|
+
class Failure < BCDD::Result
|
43
|
+
end
|
44
|
+
|
45
|
+
def self.Success: (Symbol type, untyped value) -> BCDD::Result::Success
|
46
|
+
end
|
47
|
+
|
48
|
+
class BCDD::Result
|
49
|
+
class Success < BCDD::Result
|
50
|
+
end
|
51
|
+
|
52
|
+
def self.Failure: (Symbol type, untyped value) -> BCDD::Result::Failure
|
53
|
+
end
|
54
|
+
|
55
|
+
class BCDD::Result
|
56
|
+
class Error < ::StandardError
|
57
|
+
class NotImplemented < BCDD::Result::Error
|
58
|
+
end
|
59
|
+
|
60
|
+
class MissingTypeArgument < BCDD::Result::Error
|
61
|
+
end
|
62
|
+
|
63
|
+
class UnexpectedBlockOutcome < BCDD::Result::Error
|
64
|
+
end
|
65
|
+
end
|
66
|
+
end
|
metadata
ADDED
@@ -0,0 +1,63 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: bcdd-result
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Rodrigo Serradura
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2023-09-25 00:00:00.000000000 Z
|
12
|
+
dependencies: []
|
13
|
+
description: A general-purpose result monad that allows you to create objects that
|
14
|
+
represent a success (BCDD::Result::Success) or failure (BCDD::Result::Failure).
|
15
|
+
email:
|
16
|
+
- rodrigo.serradura@gmail.com
|
17
|
+
executables: []
|
18
|
+
extensions: []
|
19
|
+
extra_rdoc_files: []
|
20
|
+
files:
|
21
|
+
- ".rubocop.yml"
|
22
|
+
- ".rubocop_todo.yml"
|
23
|
+
- CHANGELOG.md
|
24
|
+
- CODE_OF_CONDUCT.md
|
25
|
+
- LICENSE.txt
|
26
|
+
- README.md
|
27
|
+
- Rakefile
|
28
|
+
- Steepfile
|
29
|
+
- lib/bcdd/result.rb
|
30
|
+
- lib/bcdd/result/error.rb
|
31
|
+
- lib/bcdd/result/failure.rb
|
32
|
+
- lib/bcdd/result/success.rb
|
33
|
+
- lib/bcdd/result/version.rb
|
34
|
+
- sig/bcdd/result.rbs
|
35
|
+
homepage: https://github.com/b-cdd/result
|
36
|
+
licenses:
|
37
|
+
- MIT
|
38
|
+
metadata:
|
39
|
+
allowed_push_host: https://rubygems.org
|
40
|
+
homepage_uri: https://github.com/b-cdd/result
|
41
|
+
source_code_uri: https://github.com/b-cdd/result
|
42
|
+
changelog_uri: https://github.com/b-cdd/result/blob/main/CHANGELOG.md
|
43
|
+
rubygems_mfa_required: 'true'
|
44
|
+
post_install_message:
|
45
|
+
rdoc_options: []
|
46
|
+
require_paths:
|
47
|
+
- lib
|
48
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
49
|
+
requirements:
|
50
|
+
- - ">="
|
51
|
+
- !ruby/object:Gem::Version
|
52
|
+
version: 2.7.0
|
53
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
54
|
+
requirements:
|
55
|
+
- - ">="
|
56
|
+
- !ruby/object:Gem::Version
|
57
|
+
version: '0'
|
58
|
+
requirements: []
|
59
|
+
rubygems_version: 3.4.19
|
60
|
+
signing_key:
|
61
|
+
specification_version: 4
|
62
|
+
summary: A result abstraction (monad based) for Ruby.
|
63
|
+
test_files: []
|