use_cases 0.2.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (44) hide show
  1. checksums.yaml +7 -0
  2. data/.github/workflows/main.yml +23 -0
  3. data/.gitignore +12 -0
  4. data/.rspec +3 -0
  5. data/.rubocop.yml +19 -0
  6. data/.rubocop_todo.yml +28 -0
  7. data/CHANGELOG.md +20 -0
  8. data/CODE_OF_CONDUCT.md +84 -0
  9. data/Gemfile +20 -0
  10. data/Gemfile.lock +129 -0
  11. data/LICENSE.txt +21 -0
  12. data/README.md +265 -0
  13. data/Rakefile +22 -0
  14. data/bin/console +15 -0
  15. data/bin/setup +8 -0
  16. data/lib/use_case.rb +57 -0
  17. data/lib/use_cases/authorize.rb +20 -0
  18. data/lib/use_cases/base.rb +8 -0
  19. data/lib/use_cases/dsl.rb +35 -0
  20. data/lib/use_cases/errors.rb +9 -0
  21. data/lib/use_cases/module_optins.rb +43 -0
  22. data/lib/use_cases/notifications.rb +51 -0
  23. data/lib/use_cases/params.rb +15 -0
  24. data/lib/use_cases/prepare.rb +19 -0
  25. data/lib/use_cases/rspec/matchers.rb +31 -0
  26. data/lib/use_cases/stack.rb +51 -0
  27. data/lib/use_cases/stack_runner.rb +60 -0
  28. data/lib/use_cases/step_active_job_adapter.rb +34 -0
  29. data/lib/use_cases/step_adapters/abstract.rb +99 -0
  30. data/lib/use_cases/step_adapters/authorize.rb +22 -0
  31. data/lib/use_cases/step_adapters/check.rb +22 -0
  32. data/lib/use_cases/step_adapters/enqueue.rb +18 -0
  33. data/lib/use_cases/step_adapters/map.rb +18 -0
  34. data/lib/use_cases/step_adapters/step.rb +18 -0
  35. data/lib/use_cases/step_adapters/tee.rb +20 -0
  36. data/lib/use_cases/step_adapters/try.rb +20 -0
  37. data/lib/use_cases/step_adapters.rb +25 -0
  38. data/lib/use_cases/step_result.rb +55 -0
  39. data/lib/use_cases/transaction.rb +25 -0
  40. data/lib/use_cases/validate.rb +104 -0
  41. data/lib/use_cases/version.rb +5 -0
  42. data/lib/use_cases.rb +7 -0
  43. data/use_cases.gemspec +42 -0
  44. metadata +200 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: cf8f3d237d63199c6af9da931fa275833b6cadf3378548d95208f7aa11bc7a49
4
+ data.tar.gz: bc428dd162cfa152966ffb1eae6273796649baa4f8a702fe43887ce05fab26c6
5
+ SHA512:
6
+ metadata.gz: 3fef9fde7da990fd80b02754bc2f63d5550fdbb856044dd9ee8a4bdb392be814807d3ff345b5c5cae609572b10b00c57512b3b37bc3cc8812fb989726a706570
7
+ data.tar.gz: 1c5acb9f5f82918d6f79eed927d346f0bd165bb66dd3e0b6f673d8419bc34faa6b991d8066df7080ebdaf75170801c0363cacb4d6463305131e1d520bb4afbc5
@@ -0,0 +1,23 @@
1
+ name: Ruby
2
+
3
+ on: [push, pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - name: Set up Ruby
11
+ uses: ruby/setup-ruby@v1
12
+ with:
13
+ ruby-version: 2.6.8
14
+ bundler-cache: true
15
+ - name: Run tests
16
+ run: bundle exec rake
17
+ - name: Upload coverage results to CodeClimate
18
+ uses: paambaati/codeclimate-action@v2.7.5
19
+ env:
20
+ CC_TEST_REPORTER_ID: 4da939c3df4f671d70f77702b175ccd8244b208670853ac48a5d33c7b8b5a0a0
21
+ COVERAGE_FILE: coverage/.resultset.json
22
+ with:
23
+ coverage-input-type: simplecov
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ .byebug_history
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,19 @@
1
+ inherit_from: .rubocop_todo.yml
2
+
3
+ AllCops:
4
+ TargetRubyVersion: 2.6.8
5
+
6
+ Style/StringLiterals:
7
+ Enabled: true
8
+ EnforcedStyle: double_quotes
9
+
10
+ Style/StringLiteralsInInterpolation:
11
+ Enabled: true
12
+ EnforcedStyle: double_quotes
13
+
14
+ Style/Documentation:
15
+ Enabled: false
16
+
17
+ Metrics/BlockLength:
18
+ Exclude:
19
+ - "./spec/**/*"
data/.rubocop_todo.yml ADDED
@@ -0,0 +1,28 @@
1
+ # This configuration was generated by
2
+ # `rubocop --auto-gen-config`
3
+ # on 2021-09-23 08:29:51 UTC using RuboCop version 1.21.0.
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: 1
10
+ # Configuration parameters: CountComments, CountAsOne, ExcludedMethods, IgnoredMethods.
11
+ # IgnoredMethods: refine
12
+ Metrics/BlockLength:
13
+ Max: 26
14
+
15
+ # Offense count: 1
16
+ # Configuration parameters: EnforcedStyle, CheckMethodNames, CheckSymbols, AllowedIdentifiers.
17
+ # SupportedStyles: snake_case, normalcase, non_integer
18
+ # AllowedIdentifiers: capture3, iso8601, rfc1123_date, rfc822, rfc2822, rfc3339
19
+ Naming/VariableNumber:
20
+ Exclude:
21
+ - 'spec/use_cases/base_spec.rb'
22
+
23
+ # Offense count: 1
24
+ # Cop supports --auto-correct.
25
+ # Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
26
+ # URISchemes: http, https
27
+ Layout/LineLength:
28
+ Max: 171
data/CHANGELOG.md ADDED
@@ -0,0 +1,20 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2021-09-21
4
+
5
+ - Added the basic DSL of them with the following modules:
6
+ - authorize
7
+ - DSL
8
+ - Errors
9
+ - Notifications [WIP]
10
+ - StackRunner
11
+ - Stack
12
+ - StepResult
13
+ - Steps
14
+ - Validate
15
+
16
+ - Added specs to the public API (DSLs)
17
+ - Authorize DSL
18
+ - DSL
19
+ - Validate DSL
20
+ - Steps DSL
@@ -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 guilherme@listminut.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,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in use_cases.gemspec
6
+ gemspec
7
+
8
+ gem "activesupport"
9
+ gem "dry-events"
10
+ gem "dry-matcher"
11
+ gem "dry-monads"
12
+ gem "dry-validation"
13
+
14
+ group :development, :test do
15
+ gem "byebug"
16
+ gem "rake", "~> 13.0"
17
+ gem "rspec", "~> 3.0"
18
+ gem "rubocop", "~> 1.7"
19
+ gem "simplecov", require: false
20
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,129 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ use_cases (0.2.5)
5
+ activesupport
6
+ dry-events
7
+ dry-matcher
8
+ dry-monads
9
+ dry-validation
10
+
11
+ GEM
12
+ remote: https://rubygems.org/
13
+ specs:
14
+ activesupport (6.1.4.1)
15
+ concurrent-ruby (~> 1.0, >= 1.0.2)
16
+ i18n (>= 1.6, < 2)
17
+ minitest (>= 5.1)
18
+ tzinfo (~> 2.0)
19
+ zeitwerk (~> 2.3)
20
+ ast (2.4.2)
21
+ byebug (11.1.3)
22
+ concurrent-ruby (1.1.9)
23
+ diff-lcs (1.4.4)
24
+ docile (1.4.0)
25
+ dry-configurable (0.13.0)
26
+ concurrent-ruby (~> 1.0)
27
+ dry-core (~> 0.6)
28
+ dry-container (0.9.0)
29
+ concurrent-ruby (~> 1.0)
30
+ dry-configurable (~> 0.13, >= 0.13.0)
31
+ dry-core (0.7.1)
32
+ concurrent-ruby (~> 1.0)
33
+ dry-events (0.3.0)
34
+ concurrent-ruby (~> 1.0)
35
+ dry-core (~> 0.5, >= 0.5)
36
+ dry-inflector (0.2.1)
37
+ dry-initializer (3.0.4)
38
+ dry-logic (1.2.0)
39
+ concurrent-ruby (~> 1.0)
40
+ dry-core (~> 0.5, >= 0.5)
41
+ dry-matcher (0.9.0)
42
+ dry-core (~> 0.4, >= 0.4.8)
43
+ dry-monads (1.4.0)
44
+ concurrent-ruby (~> 1.0)
45
+ dry-core (~> 0.7)
46
+ dry-schema (1.8.0)
47
+ concurrent-ruby (~> 1.0)
48
+ dry-configurable (~> 0.13, >= 0.13.0)
49
+ dry-core (~> 0.5, >= 0.5)
50
+ dry-initializer (~> 3.0)
51
+ dry-logic (~> 1.0)
52
+ dry-types (~> 1.5)
53
+ dry-types (1.5.1)
54
+ concurrent-ruby (~> 1.0)
55
+ dry-container (~> 0.3)
56
+ dry-core (~> 0.5, >= 0.5)
57
+ dry-inflector (~> 0.1, >= 0.1.2)
58
+ dry-logic (~> 1.0, >= 1.0.2)
59
+ dry-validation (1.7.0)
60
+ concurrent-ruby (~> 1.0)
61
+ dry-container (~> 0.7, >= 0.7.1)
62
+ dry-core (~> 0.5, >= 0.5)
63
+ dry-initializer (~> 3.0)
64
+ dry-schema (~> 1.8, >= 1.8.0)
65
+ i18n (1.8.10)
66
+ concurrent-ruby (~> 1.0)
67
+ minitest (5.14.4)
68
+ parallel (1.21.0)
69
+ parser (3.0.2.0)
70
+ ast (~> 2.4.1)
71
+ rainbow (3.0.0)
72
+ rake (13.0.6)
73
+ regexp_parser (2.1.1)
74
+ rexml (3.2.5)
75
+ rspec (3.10.0)
76
+ rspec-core (~> 3.10.0)
77
+ rspec-expectations (~> 3.10.0)
78
+ rspec-mocks (~> 3.10.0)
79
+ rspec-core (3.10.1)
80
+ rspec-support (~> 3.10.0)
81
+ rspec-expectations (3.10.1)
82
+ diff-lcs (>= 1.2.0, < 2.0)
83
+ rspec-support (~> 3.10.0)
84
+ rspec-mocks (3.10.2)
85
+ diff-lcs (>= 1.2.0, < 2.0)
86
+ rspec-support (~> 3.10.0)
87
+ rspec-support (3.10.2)
88
+ rubocop (1.21.0)
89
+ parallel (~> 1.10)
90
+ parser (>= 3.0.0.0)
91
+ rainbow (>= 2.2.2, < 4.0)
92
+ regexp_parser (>= 1.8, < 3.0)
93
+ rexml
94
+ rubocop-ast (>= 1.9.1, < 2.0)
95
+ ruby-progressbar (~> 1.7)
96
+ unicode-display_width (>= 1.4.0, < 3.0)
97
+ rubocop-ast (1.11.0)
98
+ parser (>= 3.0.1.1)
99
+ ruby-progressbar (1.11.0)
100
+ simplecov (0.21.2)
101
+ docile (~> 1.1)
102
+ simplecov-html (~> 0.11)
103
+ simplecov_json_formatter (~> 0.1)
104
+ simplecov-html (0.12.3)
105
+ simplecov_json_formatter (0.1.3)
106
+ tzinfo (2.0.4)
107
+ concurrent-ruby (~> 1.0)
108
+ unicode-display_width (2.1.0)
109
+ zeitwerk (2.4.2)
110
+
111
+ PLATFORMS
112
+ x86_64-darwin-20
113
+ x86_64-linux
114
+
115
+ DEPENDENCIES
116
+ activesupport
117
+ byebug
118
+ dry-events
119
+ dry-matcher
120
+ dry-monads
121
+ dry-validation
122
+ rake (~> 13.0)
123
+ rspec (~> 3.0)
124
+ rubocop (~> 1.7)
125
+ simplecov
126
+ use_cases!
127
+
128
+ BUNDLED WITH
129
+ 2.2.25
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Guilherme Andrade
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,265 @@
1
+ [![Maintainability](https://api.codeclimate.com/v1/badges/b47701c9616987832bba/maintainability)](https://codeclimate.com/github/listminut/use_cases/maintainability)
2
+
3
+ [![Test Coverage](https://api.codeclimate.com/v1/badges/b47701c9616987832bba/test_coverage)](https://codeclimate.com/github/listminut/use_cases/test_coverage)
4
+
5
+ # UseCases
6
+
7
+ `UseCases` is a gem based on the [dry-transaction](https://dry-rb.org/gems/dry-transaction/) DSL that implements macros commonly used internally by Ring Twice.
8
+
9
+ `UseCases` does not however use `dry-transaction` behind the scenes. Instead it relies on other `dry` libraries like [dry-validation](https://dry-rb.org/gems/dry-validation/), [dry-events](https://dry-rb.org/gems/dry-validation/) and [dry-monads](https://dry-rb.org/gems/dry-validation/) to implement a DSL that can be flexible enough for our needs.
10
+
11
+ ## Why `UseCases` came about:
12
+
13
+ 1. It allows you to use `dry-validation` without much gymastics.
14
+ 2. It abstracts common steps like **authorization** and **validation** into macros.
15
+ 3. It solves what we consider a problem of `dry-transaction`. The way it funnels down `input` through `Dry::Monads` payloads alone. `UseCases` offers more flexibility in a way that still promotes functional programming values.
16
+
17
+ ## Installation
18
+
19
+ Add this line to your application's Gemfile:
20
+
21
+ ```ruby
22
+ gem 'use_cases'
23
+ ```
24
+
25
+ And then execute:
26
+
27
+ $ bundle install
28
+
29
+ Or install it yourself as:
30
+
31
+ $ gem install use_cases
32
+
33
+ ## Usage
34
+
35
+ To fully understand `UseCases`, make sure to read [dry-transaction](https://dry-rb.org/gems/dry-transaction/0.13/)'s documentation first.
36
+
37
+ ### Validations
38
+
39
+ See [dry-validation](https://dry-rb.org/gems/dry-validation/)
40
+
41
+ ### Step Adapters
42
+
43
+ https://dry-rb.org/gems/dry-transaction/0.13/step-adapters/
44
+
45
+ **Basic Example**
46
+
47
+ ```ruby
48
+ class YourCase < UseCases::Base
49
+ params {}
50
+
51
+ step :do_something
52
+
53
+ def do_something(params, current_user)
54
+ params[:should_fail] ? Failure([:failed, "failed"]) : Success("it succeeds!")
55
+ end
56
+ end
57
+
58
+ params = { should_fail: true }
59
+
60
+ YourCase.new.call(params, nil) do |match|
61
+ match.failure :failed do |(code, result)|
62
+ puts code
63
+ end
64
+
65
+ match.success do |message|
66
+ puts message
67
+ end
68
+ end
69
+ # => failed
70
+
71
+ params = { should_fail: false }
72
+
73
+ YourCase.new.call(params, nil) do |match|
74
+ match.failure :failed do |(code, result)|
75
+ puts code
76
+ end
77
+
78
+ match.success do |message|
79
+ puts message
80
+ end
81
+ end
82
+ # => it succeeds!
83
+ ```
84
+
85
+ **Complex Example**
86
+
87
+ ```ruby
88
+ class YourCase < UseCases::Base
89
+ params {}
90
+
91
+ try :load_some_resource
92
+
93
+ step :change_this_resource
94
+
95
+ tee :log_a_message
96
+
97
+ check :user_can_create_another_resource?
98
+
99
+ map :create_some_already_validated_resource
100
+
101
+ enqueue :send_email_to_user
102
+
103
+ private
104
+
105
+ def load_some_resource(_, params)
106
+ Resource.find(params[:id])
107
+ end
108
+
109
+ def change_this_resource(resource, params)
110
+ resource.text = params[:new_text]
111
+
112
+ if resource.text == params[:new_text]
113
+ Success(resource)
114
+ else
115
+ Failure([:failed, "could not update resource"])
116
+ end
117
+ end
118
+
119
+ def log_a_message(resource)
120
+ Logger.info('Resource updated')
121
+ end
122
+
123
+ def user_can_create_another_resource?(_, _, user)
124
+ user.can_create?(Resource)
125
+ end
126
+
127
+ def create_some_already_validated_resource(resource, params, user)
128
+ new_resource = Resource.create(text: params[:text])
129
+ end
130
+
131
+ def send_email_to_user(new_resource, _, user)
132
+ ResourcEMailer.notify_user(user, new_resource).deliver!
133
+ end
134
+ end
135
+ ```
136
+
137
+ ### Authorization
138
+
139
+ `authorize` is a `check` step that returns an `:unauthorized` code in it's `Failure`.
140
+
141
+ **Example**
142
+
143
+ ```ruby
144
+ class YourCase < UseCases::Base
145
+ authorize 'User must be over 18' do |user|
146
+ user.age >= 18
147
+ end
148
+ end
149
+
150
+ user = User.where('age = 15').first
151
+
152
+ YourCase.new.call({}, user) do |match|
153
+ match.failure :unauthorized do |(code, result)|
154
+ puts code
155
+ end
156
+ end
157
+ # => User must be over 18
158
+ ```
159
+
160
+ ### Example
161
+
162
+ For the case of creating posts within a thread.
163
+
164
+ **Specs**
165
+
166
+ - Only active users or the thread owner can post.
167
+ - The post must be between 25 and 150 characters.
168
+ - The post must be sanitized to remove any sensitive or explicit content.
169
+ - The post must be saved to the database in the end.
170
+ - In case any conditions are not met, an failure should be returned with it's own error code.
171
+
172
+ ```ruby
173
+ class Posts::Create < UseCases::Base
174
+
175
+ params do
176
+ required(:body).filled(:string).value(size?: 25..150)
177
+ required(:thread_id).filled(:integer)
178
+ end
179
+
180
+ try :load_post_thread, failure: :not_found
181
+
182
+ authorize 'User is not active' do |user, params, thread|
183
+ user.active?
184
+ end
185
+
186
+ authorize 'User must be active or the thread author.' do |user, params, thread|
187
+ user.active? || thread.author == user
188
+ end
189
+
190
+ step :sanitize_body
191
+
192
+ step :create_post
193
+
194
+ private
195
+
196
+ def load_post_thread(params, user)
197
+ Thread.find(params[:thread_id])
198
+ end
199
+
200
+ def sanitize_body(params)
201
+ SanitizeText.new.call(params[:body]).to_monad
202
+ end
203
+
204
+ def create_post(body, params, user)
205
+ post = Post.new(body: body, user_id: user.id, thread_id: params[:thread_id])
206
+
207
+ post.save ? Success(post) : Failure([:failed_to_save, post.errors.details])
208
+ end
209
+ end
210
+ ```
211
+
212
+ And in your controller action
213
+
214
+ ```ruby
215
+ # app/controllers/posts_controller.rb
216
+ class PostsController < ApplicationController
217
+ def create
218
+ Posts::Create.new.call(params, current_user) do |match|
219
+
220
+ # in success, the return value is the Success payload of the last step (#create_post)
221
+ match.success do |post|
222
+ # result => <Post:>
223
+ end
224
+
225
+ # in case ::params or any other dry-validation fails.
226
+ match.failure :validation_error do |result|
227
+ # result => [:validation_error, ['validation_error', { thread_id: 'is missing' }]
228
+ end
229
+
230
+ # in case ::try raises an error (ActiveRecord::NotFound in this case)
231
+ match.failure :not_found do |result|
232
+ # result => [:not_found, ['not_found', 'Could not find thread with id='<params[:thread_id]>'']
233
+ end
234
+
235
+ # in case any of the ::authorize blocks returns false
236
+ match.failure :unauthorized do |result|
237
+ # result => [:unauthorized, ['unauthorized', 'User is not active']
238
+ end
239
+
240
+ # in case #create_post returns a Failure
241
+ match.failure :failed_to_save do |result|
242
+ # result => [:failed_to_save, ['failed_to_save', { user_id: 'some error' }]
243
+ end
244
+ end
245
+ end
246
+ end
247
+ ```
248
+
249
+ ## Development
250
+
251
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
252
+
253
+ 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).
254
+
255
+ ## Contributing
256
+
257
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/use_cases. 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/[USERNAME]/use_cases/blob/master/CODE_OF_CONDUCT.md).
258
+
259
+ ## License
260
+
261
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
262
+
263
+ ## Code of Conduct
264
+
265
+ Everyone interacting in the UseCases project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/use_cases/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+ require "simplecov"
6
+
7
+ RSpec::Core::RakeTask.new(:spec)
8
+
9
+ require "rubocop/rake_task"
10
+
11
+ RuboCop::RakeTask.new
12
+
13
+ task default: %i[spec rubocop]
14
+
15
+ namespace :coverage do
16
+ desc "Collates all result sets generated by the different test runners"
17
+ task :report do
18
+ require "simplecov"
19
+
20
+ SimpleCov.collate Dir["simplecov-resultset-*/.resultset.json"]
21
+ end
22
+ end
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "use_cases"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here