sorbet-result 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (50) hide show
  1. checksums.yaml +7 -0
  2. data/.rubocop.yml +28 -0
  3. data/.ruby-version +1 -0
  4. data/.tool-versions +1 -0
  5. data/CHANGELOG.md +14 -0
  6. data/CODE_OF_CONDUCT.md +84 -0
  7. data/Gemfile +24 -0
  8. data/Gemfile.lock +104 -0
  9. data/LICENSE.txt +21 -0
  10. data/README.md +139 -0
  11. data/Rakefile +24 -0
  12. data/lib/sorbet-result.rb +11 -0
  13. data/lib/t/failure.rb +43 -0
  14. data/lib/t/nil_payload_error.rb +14 -0
  15. data/lib/t/no_payload_on_failure_error.rb +14 -0
  16. data/lib/t/result.rb +31 -0
  17. data/lib/t/success.rb +48 -0
  18. data/sorbet/config +4 -0
  19. data/sorbet/rbi/annotations/rainbow.rbi +269 -0
  20. data/sorbet/rbi/gems/ast@2.4.2.rbi +584 -0
  21. data/sorbet/rbi/gems/diff-lcs@1.5.0.rbi +1083 -0
  22. data/sorbet/rbi/gems/io-console@0.6.0.rbi +8 -0
  23. data/sorbet/rbi/gems/irb@1.6.4.rbi +342 -0
  24. data/sorbet/rbi/gems/json@2.6.3.rbi +1533 -0
  25. data/sorbet/rbi/gems/minitest@5.18.0.rbi +1491 -0
  26. data/sorbet/rbi/gems/netrc@0.11.0.rbi +158 -0
  27. data/sorbet/rbi/gems/parallel@1.22.1.rbi +277 -0
  28. data/sorbet/rbi/gems/parser@3.2.2.0.rbi +7253 -0
  29. data/sorbet/rbi/gems/rainbow@3.1.1.rbi +402 -0
  30. data/sorbet/rbi/gems/rake@13.0.6.rbi +3024 -0
  31. data/sorbet/rbi/gems/rbi@0.0.16.rbi +3008 -0
  32. data/sorbet/rbi/gems/regexp_parser@2.7.0.rbi +3580 -0
  33. data/sorbet/rbi/gems/reline@0.3.3.rbi +8 -0
  34. data/sorbet/rbi/gems/rexml@3.2.5.rbi +4717 -0
  35. data/sorbet/rbi/gems/rubocop-ast@1.28.0.rbi +6987 -0
  36. data/sorbet/rbi/gems/rubocop-minitest@0.30.0.rbi +2485 -0
  37. data/sorbet/rbi/gems/rubocop-rake@0.6.0.rbi +328 -0
  38. data/sorbet/rbi/gems/rubocop-sorbet@0.7.0.rbi +1043 -0
  39. data/sorbet/rbi/gems/rubocop@1.50.2.rbi +55147 -0
  40. data/sorbet/rbi/gems/ruby-progressbar@1.13.0.rbi +1317 -0
  41. data/sorbet/rbi/gems/spoom@1.2.1.rbi +2503 -0
  42. data/sorbet/rbi/gems/tapioca@0.11.5.rbi +3268 -0
  43. data/sorbet/rbi/gems/thor@1.2.1.rbi +3956 -0
  44. data/sorbet/rbi/gems/unicode-display_width@2.4.2.rbi +65 -0
  45. data/sorbet/rbi/gems/unparser@0.6.7.rbi +4524 -0
  46. data/sorbet/rbi/gems/yard-sorbet@0.8.1.rbi +428 -0
  47. data/sorbet/rbi/gems/yard@0.9.34.rbi +18219 -0
  48. data/sorbet/tapioca/config.yml +13 -0
  49. data/sorbet/tapioca/require.rb +4 -0
  50. metadata +110 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7ccd5a2608d32086b0266b9fe940859619017347dc299d05bb49378c621e804e
4
+ data.tar.gz: 8fb081fd6236e7670de6e43e9703d4c37c6b64919710e80af9950de1233f2b17
5
+ SHA512:
6
+ metadata.gz: 88e927e89b348ee44075411233d0d97c551b3be5cb37654189c838332803559aecf030d8780e2b668834bdec133154538b7fb7e92694c58d0ef05722cf4e7532
7
+ data.tar.gz: 2fbaa5dba370f482ad70fe051ed75791b37478d446a225bb9af0f2eed51dcca9bd1b83e977e4e5826be827d5f75f64a9a3a708ee05e7de6dcc18ccc43be75354
data/.rubocop.yml ADDED
@@ -0,0 +1,28 @@
1
+ inherit_mode:
2
+ merge:
3
+ - Exclude
4
+
5
+ require:
6
+ - rubocop-minitest
7
+ - rubocop-rake
8
+ - rubocop-sorbet
9
+
10
+ AllCops:
11
+ NewCops: enable
12
+ TargetRubyVersion: 2.7
13
+ Exclude:
14
+ - sorbet/**/*.rbi
15
+
16
+ Style/AccessorGrouping:
17
+ Enabled: false
18
+
19
+ Style/StringLiterals:
20
+ Enabled: true
21
+ EnforcedStyle: double_quotes
22
+
23
+ Style/StringLiteralsInInterpolation:
24
+ Enabled: true
25
+ EnforcedStyle: double_quotes
26
+
27
+ Layout/LineLength:
28
+ Max: 120
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.2.2
data/.tool-versions ADDED
@@ -0,0 +1 @@
1
+ ruby 3.2.2
data/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+ All notable changes to this project will be documented in this file.
3
+
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2023-04-17
10
+
11
+ ### Added
12
+
13
+ - `T::Result`, `T::Success` and `T::Failure` types.
14
+ - Basic documentation.
@@ -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 maxveldink@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/Gemfile ADDED
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in activerecord-ejection_seat.gemspec
6
+ gemspec
7
+
8
+ group :development do
9
+ gem "rake"
10
+ gem "rubocop"
11
+ gem "rubocop-minitest"
12
+ gem "rubocop-rake"
13
+ gem "rubocop-sorbet"
14
+ gem "sorbet"
15
+ gem "spoom"
16
+ gem "tapioca", require: false
17
+ end
18
+
19
+ group :development, :test do
20
+ gem "minitest"
21
+ gem "sorbet-runtime"
22
+
23
+ gem "debug"
24
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,104 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ sorbet-result (0.1.0)
5
+ sorbet-runtime
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ ast (2.4.2)
11
+ debug (1.7.2)
12
+ irb (>= 1.5.0)
13
+ reline (>= 0.3.1)
14
+ diff-lcs (1.5.0)
15
+ io-console (0.6.0)
16
+ irb (1.6.4)
17
+ reline (>= 0.3.0)
18
+ json (2.6.3)
19
+ minitest (5.18.0)
20
+ netrc (0.11.0)
21
+ parallel (1.22.1)
22
+ parser (3.2.2.0)
23
+ ast (~> 2.4.1)
24
+ rainbow (3.1.1)
25
+ rake (13.0.6)
26
+ rbi (0.0.16)
27
+ ast
28
+ parser (>= 2.6.4.0)
29
+ sorbet-runtime (>= 0.5.9204)
30
+ unparser
31
+ regexp_parser (2.7.0)
32
+ reline (0.3.3)
33
+ io-console (~> 0.5)
34
+ rexml (3.2.5)
35
+ rubocop (1.50.2)
36
+ json (~> 2.3)
37
+ parallel (~> 1.10)
38
+ parser (>= 3.2.0.0)
39
+ rainbow (>= 2.2.2, < 4.0)
40
+ regexp_parser (>= 1.8, < 3.0)
41
+ rexml (>= 3.2.5, < 4.0)
42
+ rubocop-ast (>= 1.28.0, < 2.0)
43
+ ruby-progressbar (~> 1.7)
44
+ unicode-display_width (>= 2.4.0, < 3.0)
45
+ rubocop-ast (1.28.0)
46
+ parser (>= 3.2.1.0)
47
+ rubocop-minitest (0.30.0)
48
+ rubocop (>= 1.39, < 2.0)
49
+ rubocop-rake (0.6.0)
50
+ rubocop (~> 1.0)
51
+ rubocop-sorbet (0.7.0)
52
+ rubocop (>= 0.90.0)
53
+ ruby-progressbar (1.13.0)
54
+ sorbet (0.5.10782)
55
+ sorbet-static (= 0.5.10782)
56
+ sorbet-runtime (0.5.10782)
57
+ sorbet-static (0.5.10782-universal-darwin-22)
58
+ sorbet-static (0.5.10782-x86_64-linux)
59
+ sorbet-static-and-runtime (0.5.10782)
60
+ sorbet (= 0.5.10782)
61
+ sorbet-runtime (= 0.5.10782)
62
+ spoom (1.2.1)
63
+ sorbet (>= 0.5.10187)
64
+ sorbet-runtime (>= 0.5.9204)
65
+ thor (>= 0.19.2)
66
+ tapioca (0.11.5)
67
+ bundler (>= 2.2.25)
68
+ netrc (>= 0.11.0)
69
+ parallel (>= 1.21.0)
70
+ rbi (~> 0.0.0, >= 0.0.16)
71
+ sorbet-static-and-runtime (>= 0.5.10187)
72
+ spoom (~> 1.2.0, >= 1.2.0)
73
+ thor (>= 1.2.0)
74
+ yard-sorbet
75
+ thor (1.2.1)
76
+ unicode-display_width (2.4.2)
77
+ unparser (0.6.7)
78
+ diff-lcs (~> 1.3)
79
+ parser (>= 3.2.0)
80
+ yard (0.9.34)
81
+ yard-sorbet (0.8.1)
82
+ sorbet-runtime (>= 0.5)
83
+ yard (>= 0.9)
84
+
85
+ PLATFORMS
86
+ arm64-darwin-22
87
+ x86_64-linux
88
+
89
+ DEPENDENCIES
90
+ debug
91
+ minitest
92
+ rake
93
+ rubocop
94
+ rubocop-minitest
95
+ rubocop-rake
96
+ rubocop-sorbet
97
+ sorbet
98
+ sorbet-result!
99
+ sorbet-runtime
100
+ spoom
101
+ tapioca
102
+
103
+ BUNDLED WITH
104
+ 2.4.12
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Max VelDink
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,139 @@
1
+ # T::Result, T::Success and T::Failure
2
+
3
+ A simple, strongly-typed monad for modeling results, helping you implement [Railway Oriented Programming concepts](https://blog.logrocket.com/what-is-railway-oriented-programming/) in Ruby. Helps alleviate error-driven development, all the while boosting your confidence with Sorbet static checks.
4
+
5
+ ## Installation
6
+
7
+ Install the gem and add to the application's Gemfile by executing:
8
+
9
+ $ bundle add sorbet-result
10
+
11
+ If bundler is not being used to manage dependencies, install the gem by executing:
12
+
13
+ $ gem install sorbet-result
14
+
15
+ ## Usage
16
+
17
+ Using a basic Result in your methods is as simple as indicating something could return a `T::Result`.
18
+
19
+ ```ruby
20
+ sig { params(resource_id: Integer).returns(T::Result) }
21
+ def call_api(resource_id)
22
+ # something bad happened
23
+ return T::Failure.new
24
+
25
+ # something other bad thing happened
26
+ return T::Failure.new
27
+
28
+ # Success!
29
+ T::Success.new
30
+ end
31
+ ```
32
+
33
+ Generally, it's nice to have a payload with results, and it's nice to have more information on failures. We can indicate what types these are in our signatures for better static checks. Note that payloads and errors can be _any_ type.
34
+
35
+ ```ruby
36
+ sig { params(resource_id: Integer).returns(T::Result[Float, String]) }
37
+ def call_api(resource_id)
38
+ # something bad happened
39
+ return T::Failure.new(error: "I couldn't do it!")
40
+
41
+ # something other bad thing happened
42
+ return T::Failure.new(error: "I couldn't do it for another reason!")
43
+
44
+ # Success!
45
+ T::Success.new(payload: 1.12)
46
+ end
47
+ ```
48
+
49
+ *Note:* We use Sorbet's generics for payload and error typing. The generic payload and error types are erased at runtime, so you won't get a type error at runtime if you violate the generic types. These types will help you statically so be sure to run `srb tc` on your project.
50
+
51
+ Further, if another part of your program needs the Result, it can depend on _only_ `T::Success`es (or `T::Failure`s if you're doing something with those results).
52
+
53
+ ```ruby
54
+ sig { params(success_result: T::Success).void }
55
+ def do_something_with_resource(success_result)
56
+ ...
57
+ end
58
+ ```
59
+
60
+ Finally, there are a few methods you can use on both `T::Result` types.
61
+
62
+ ```ruby
63
+ result = call_api(1)
64
+
65
+ result.success? # => true if success, false if failure
66
+ result.failure? # => true if failure, false if success
67
+
68
+ result.error # => nil on success, nil or error type on failure
69
+
70
+ result.payload # => nil on failure, nil or payload type on failure
71
+
72
+ result.payload! # => payload type or raises NilPayloadError on success, raises NoPayloadOnFailureError on failure
73
+ ```
74
+
75
+ The `payload!` method is useful if you don't want to do a `T.must` escape hatch, since the payload _could_ always be `nil`. If you're writing Railway inspired code, you should do the `success?` check before calling `payload!` and know that you've returned a payload on the Result.
76
+
77
+ ### Why use Results?
78
+
79
+ Let's say you're working on a method that reaches out to an API and fetches a resource. We hope to get a successful response and continue on in our program, but you can imagine several scenarios where we don't get that response: our authentication could fail, the server could return a 5XX response code, or the resource we were querying could have moved or not exist any more.
80
+
81
+ You might be tempted to use exceptions to model these "off-ramps" from the method.
82
+
83
+ ```ruby
84
+ sig { params(resource_id: Integer).returns(Float) }
85
+ def call_api(resource_id)
86
+ # something bad happened
87
+ raise ArgumentError
88
+
89
+ # something other bad thing happened
90
+ raise StandardError
91
+
92
+ # Success!
93
+ 1.12
94
+ end
95
+ ```
96
+
97
+ This has several downsides; primarily, this required your caller to _know_ what exceptions to watch out for, or risk bubbling the error all the way out of your program when you could have recovered from it. Our Sorbet signature also becomes less helpful, as we can't indicate what errors could be raised here.
98
+
99
+ Railway Oriented Programming, which comes from the functional programming community, alleviates this by _expecting_ the failure states and making them a part of the normal flow of a method. Most errors are recoverable; at the very least we can message them back to the user in some way. We should inform the caller with a Result that could be either a Success or Failure, and allow them continue or take an "off-ramp" with a failure message. If we embrace this style of programming, our `call_api` method turns into this:
100
+
101
+ ```ruby
102
+ sig { params(resource_id: Integer).returns(T::Result[Float, String]) }
103
+ def call_api(resource_id)
104
+ # something bad happened
105
+ return T::Failure.new(error: "I couldn't do it!")
106
+
107
+ # something other bad thing happened
108
+ return T::Failure.new(error: "I couldn't do it for another reason!")
109
+
110
+ # Success!
111
+ T::Success.new(payload: 1.12)
112
+ end
113
+ ```
114
+
115
+ Sorbet is useful here now, as it the signature covers all possible return values and informs the caller what it should do: check the result status first, then do something with the error or payload. Statically, Sorbet will also know the types associated with our Result for better typechecking across the codebase.
116
+
117
+ Our caller doesn't need to guess which errors to rescue from (or doesn't need to be paranoid about rescuing all errors) and can proceed in both a success and a failure case.
118
+
119
+ ## Development
120
+
121
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake` to run Rubocop and the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
122
+
123
+ To install this gem onto your local machine, run `bundle exec rake install`.
124
+
125
+ ## Contributing
126
+
127
+ Bug reports and pull requests are welcome on GitHub at https://github.com/maxveldink/sorbet-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/maxveldink/sorbet-result/blob/master/CODE_OF_CONDUCT.md).
128
+
129
+ ## License
130
+
131
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
132
+
133
+ ## Code of Conduct
134
+
135
+ Everyone interacting in this project's codebase, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/maxveldink/sorbet-result/blob/master/CODE_OF_CONDUCT.md).
136
+
137
+ ## Sponsorships
138
+
139
+ I love creating in the open. If you find this or any other [maxveld.ink](https://maxveld.ink) content useful, please consider sponsoring me on [GitHub](https://github.com/sponsors/maxveldink).
data/Rakefile ADDED
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create do |t|
7
+ t.test_globs = ["test/**/*_test.rb"]
8
+ end
9
+
10
+ require "rubocop/rake_task"
11
+
12
+ RuboCop::RakeTask.new
13
+
14
+ desc "Run tapioca compilers"
15
+ task :tapioca do
16
+ sh "bin/tapioca gem"
17
+ end
18
+
19
+ desc "Run Sorbet typechecker"
20
+ task :sorbet do
21
+ sh "bundle exec srb tc"
22
+ end
23
+
24
+ task default: %i[rubocop:autocorrect_all sorbet test]
@@ -0,0 +1,11 @@
1
+ # rubocop:disable Naming/FileName
2
+ # rubocop:enable Naming/FileName
3
+ # typed: strict
4
+ # frozen_string_literal: true
5
+
6
+ require "sorbet-runtime"
7
+ require "t/result"
8
+ require "t/nil_payload_error"
9
+ require "t/success"
10
+ require "t/no_payload_on_failure_error"
11
+ require "t/failure"
data/lib/t/failure.rb ADDED
@@ -0,0 +1,43 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ module T
5
+ # Represents a failed result. Contains error information but no payload.
6
+ class Failure
7
+ extend Sig
8
+ extend Generic
9
+
10
+ include Result
11
+
12
+ Payload = type_member
13
+ Error = type_member
14
+
15
+ sig { override.returns(T.nilable(Error)) }
16
+ attr_reader :error
17
+
18
+ sig { params(error: T.nilable(Error)).void }
19
+ def initialize(error: nil)
20
+ @error = error
21
+ end
22
+
23
+ sig { override.returns(Boolean) }
24
+ def success?
25
+ false
26
+ end
27
+
28
+ sig { override.returns(Boolean) }
29
+ def failure?
30
+ true
31
+ end
32
+
33
+ sig { override.returns(T.nilable(Payload)) }
34
+ def payload
35
+ nil
36
+ end
37
+
38
+ sig { override.returns(Payload) }
39
+ def payload!
40
+ raise NoPayloadOnFailureError
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,14 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ module T
5
+ # Error when user attempts to unwrap payload for Success Result without payload.
6
+ class NilPayloadError < StandardError
7
+ extend Sig
8
+
9
+ sig { void }
10
+ def initialize
11
+ super("Attempted to unwrap payload from a Success Result where payload is nil. If you need to return a value, make sure the Result is initialized with a payload.") # rubocop:disable Layout/LineLength
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,14 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ module T
5
+ # Error when user attempts to access payload from a Failure Result.
6
+ class NoPayloadOnFailureError < StandardError
7
+ extend Sig
8
+
9
+ sig { void }
10
+ def initialize
11
+ super("Attempted to access a payload from a Failure Result. You were probably expecting a Success Result. Check the result with #success? or #failure? before attempting to access the payload.") # rubocop:disable Layout/LineLength
12
+ end
13
+ end
14
+ end
data/lib/t/result.rb ADDED
@@ -0,0 +1,31 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ module T
5
+ # A monad representing either a success or a failure. Contains payload and error information as well.
6
+ module Result
7
+ extend Sig
8
+ extend Helpers
9
+ extend Generic
10
+
11
+ interface!
12
+
13
+ Payload = type_member
14
+ Error = type_member
15
+
16
+ sig { abstract.returns(Boolean) }
17
+ def success?; end
18
+
19
+ sig { abstract.returns(Boolean) }
20
+ def failure?; end
21
+
22
+ sig { abstract.returns(T.nilable(Payload)) }
23
+ def payload; end
24
+
25
+ sig { abstract.returns(T.nilable(Error)) }
26
+ def error; end
27
+
28
+ sig { abstract.returns(Payload) }
29
+ def payload!; end
30
+ end
31
+ end
data/lib/t/success.rb ADDED
@@ -0,0 +1,48 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ module T
5
+ # Represents a successful result. Contains a payload and no error information.
6
+ class Success
7
+ extend Sig
8
+ extend Generic
9
+
10
+ include Result
11
+
12
+ Payload = type_member
13
+ Error = type_member
14
+
15
+ sig { override.returns(T.nilable(Payload)) }
16
+ attr_reader :payload
17
+
18
+ sig { params(payload: T.nilable(Payload)).void }
19
+ def initialize(payload: nil)
20
+ @payload = payload
21
+ end
22
+
23
+ sig { override.returns(Boolean) }
24
+ def success?
25
+ true
26
+ end
27
+
28
+ sig { override.returns(Boolean) }
29
+ def failure?
30
+ false
31
+ end
32
+
33
+ sig { override.returns(NilClass) }
34
+ def error
35
+ nil
36
+ end
37
+
38
+ sig { override.returns(Payload) }
39
+ def payload!
40
+ case @payload
41
+ when nil
42
+ raise NilPayloadError
43
+ else
44
+ @payload
45
+ end
46
+ end
47
+ end
48
+ end
data/sorbet/config ADDED
@@ -0,0 +1,4 @@
1
+ --dir
2
+ .
3
+ --ignore=tmp/
4
+ --ignore=vendor/