dry-transaction-extra 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 655e43f9df76abfb9b93f04cf55ea437635662ffcfef58b78d1227f63d8560af
4
+ data.tar.gz: 8343148513834477223867d864b9270f85109780b64ccbcd182373694cc2bd6b
5
+ SHA512:
6
+ metadata.gz: ff3ce715ed177028996635b2bac116604447266d0952f7ef8ed33c1b69f3d727b3171903310233768d086af583b3103d258910cc34365b012ef57450f6faccf5
7
+ data.tar.gz: 07012d6bbd9be48f99646389d020c90c92a9efdf02da014f66e3cccc04540fb122bf7ddbc26a2cbc5799a9c1d1671fb7399d2e0278f50b2a734004d7b816e73a
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,35 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.2
3
+
4
+ Layout/LineLength:
5
+ Max: 120
6
+
7
+ Lint/AmbiguousBlockAssociation:
8
+ Exclude:
9
+ - "spec/**/*" # `expect { }.to change { }` is fine
10
+
11
+ Metrics/BlockLength:
12
+ Exclude:
13
+ - Gemfile
14
+ - Guardfile
15
+ AllowedMethods:
16
+ - configure
17
+ - context
18
+ - define
19
+ - describe
20
+ - factory
21
+ - it
22
+ - namespace
23
+ - specify
24
+ - task
25
+ - shared_examples_for
26
+ - shared_context
27
+ - feature
28
+
29
+ Style/StringLiterals:
30
+ Enabled: true
31
+ EnforcedStyle: double_quotes
32
+
33
+ Style/StringLiteralsInInterpolation:
34
+ Enabled: true
35
+ EnforcedStyle: double_quotes
@@ -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 psadauskas@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,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in dry-transaction-extra.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.21"
data/Gemfile.lock ADDED
@@ -0,0 +1,112 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ dry-transaction-extra (0.1.0)
5
+ dry-monads (~> 1.3)
6
+ dry-transaction (~> 0.15)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ ast (2.4.2)
12
+ concurrent-ruby (1.1.10)
13
+ diff-lcs (1.5.0)
14
+ dry-configurable (1.0.1)
15
+ dry-core (~> 1.0, < 2)
16
+ zeitwerk (~> 2.6)
17
+ dry-container (0.11.0)
18
+ concurrent-ruby (~> 1.0)
19
+ dry-core (1.0.0)
20
+ concurrent-ruby (~> 1.0)
21
+ zeitwerk (~> 2.6)
22
+ dry-events (1.0.1)
23
+ concurrent-ruby (~> 1.0)
24
+ dry-core (~> 1.0, < 2)
25
+ dry-inflector (1.0.0)
26
+ dry-initializer (3.1.1)
27
+ dry-logic (1.5.0)
28
+ concurrent-ruby (~> 1.0)
29
+ dry-core (~> 1.0, < 2)
30
+ zeitwerk (~> 2.6)
31
+ dry-matcher (0.10.0)
32
+ dry-core (~> 1.0)
33
+ dry-monads (1.6.0)
34
+ concurrent-ruby (~> 1.0)
35
+ dry-core (~> 1.0, < 2)
36
+ zeitwerk (~> 2.6)
37
+ dry-schema (1.13.0)
38
+ concurrent-ruby (~> 1.0)
39
+ dry-configurable (~> 1.0, >= 1.0.1)
40
+ dry-core (~> 1.0, < 2)
41
+ dry-initializer (~> 3.0)
42
+ dry-logic (>= 1.5, < 2)
43
+ dry-types (>= 1.7, < 2)
44
+ zeitwerk (~> 2.6)
45
+ dry-transaction (0.15.0)
46
+ dry-core (~> 1.0)
47
+ dry-events (~> 1.0)
48
+ dry-matcher (~> 0.10)
49
+ dry-monads (~> 1.6)
50
+ dry-types (1.7.0)
51
+ concurrent-ruby (~> 1.0)
52
+ dry-core (~> 1.0, < 2)
53
+ dry-inflector (~> 1.0, < 2)
54
+ dry-logic (>= 1.4, < 2)
55
+ zeitwerk (~> 2.6)
56
+ dry-validation (1.10.0)
57
+ concurrent-ruby (~> 1.0)
58
+ dry-core (~> 1.0, < 2)
59
+ dry-initializer (~> 3.0)
60
+ dry-schema (>= 1.12, < 2)
61
+ zeitwerk (~> 2.6)
62
+ json (2.6.3)
63
+ parallel (1.22.1)
64
+ parser (3.2.0.0)
65
+ ast (~> 2.4.1)
66
+ rainbow (3.1.1)
67
+ rake (13.0.6)
68
+ regexp_parser (2.6.1)
69
+ rexml (3.2.5)
70
+ rspec (3.12.0)
71
+ rspec-core (~> 3.12.0)
72
+ rspec-expectations (~> 3.12.0)
73
+ rspec-mocks (~> 3.12.0)
74
+ rspec-core (3.12.0)
75
+ rspec-support (~> 3.12.0)
76
+ rspec-expectations (3.12.2)
77
+ diff-lcs (>= 1.2.0, < 2.0)
78
+ rspec-support (~> 3.12.0)
79
+ rspec-mocks (3.12.2)
80
+ diff-lcs (>= 1.2.0, < 2.0)
81
+ rspec-support (~> 3.12.0)
82
+ rspec-support (3.12.0)
83
+ rubocop (1.43.0)
84
+ json (~> 2.3)
85
+ parallel (~> 1.10)
86
+ parser (>= 3.2.0.0)
87
+ rainbow (>= 2.2.2, < 4.0)
88
+ regexp_parser (>= 1.8, < 3.0)
89
+ rexml (>= 3.2.5, < 4.0)
90
+ rubocop-ast (>= 1.24.1, < 2.0)
91
+ ruby-progressbar (~> 1.7)
92
+ unicode-display_width (>= 2.4.0, < 3.0)
93
+ rubocop-ast (1.24.1)
94
+ parser (>= 3.1.1.0)
95
+ ruby-progressbar (1.11.0)
96
+ unicode-display_width (2.4.2)
97
+ zeitwerk (2.6.6)
98
+
99
+ PLATFORMS
100
+ x86_64-linux
101
+
102
+ DEPENDENCIES
103
+ dry-container (~> 0.7)
104
+ dry-schema (~> 1.10)
105
+ dry-transaction-extra!
106
+ dry-validation (~> 1.8)
107
+ rake (~> 13.0)
108
+ rspec (~> 3.0)
109
+ rubocop (~> 1.21)
110
+
111
+ BUNDLED WITH
112
+ 2.4.2
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Paul Sadauskas
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,289 @@
1
+ # Dry::Transaction::Extra
2
+
3
+ Dry::Transaction comes with a limited set of steps. This gem defines a few more steps that are useful for getting the most out of Transactions.
4
+
5
+ ## Installation
6
+
7
+
8
+ Install the gem and add to the application's Gemfile by executing:
9
+
10
+ $ bundle add dry-transaction-extra
11
+
12
+ If bundler is not being used to manage dependencies, install the gem by executing:
13
+
14
+ $ gem install dry-transaction-extra
15
+
16
+ ## Usage
17
+
18
+ By requiring the gem, you get a few additional Step adapters registered with dry-transaction, and can begin using them immediately.
19
+
20
+ ```ruby
21
+ require "dry-transaction-extra"
22
+ ```
23
+
24
+ ### Additional Steps
25
+
26
+ Dry::Transaction::Extra defines a few extra steps you can use:
27
+
28
+ * [merge][#merge] -- Merges the output of the step with the input args. Best used with keyword arguments.
29
+ * [tap][#tap] -- Similar to Ruby `Kernel#tap`, discards the return value of the step
30
+ and returns the original input. If the step fails, then returns the Failure
31
+ instead.
32
+ * [valid][#valid] -- Runs a Dry::Schema or Dry::Validation::Contract on the input, and transforms the validation Result to a Result monad.
33
+
34
+ #### `merge`
35
+
36
+ If you're using keyword args as the arguments to your steps, you often want a
37
+ step to add its output to those args, while keeping the original kwargs intact.
38
+
39
+ * If the output of the step is a Hash, then that hash is merged into the input.
40
+ * If the output of the step is not a Hash, then a key is inferred from the
41
+ step name. The name of the key can be overridden with the `as:` option.
42
+
43
+ ##### Merging Hash output
44
+
45
+ ```ruby
46
+ merge :add_context
47
+
48
+ # Input: { user: #<User id:42>, account: #<Account id:1> }
49
+ def add_context(user:, **)
50
+ {
51
+ email: user.email,
52
+ token: UserToken.lookup(user)
53
+ }
54
+ end
55
+ # Output: { user: #<User id:42>, account: #<Account id:1>, email: "paul@myapp.example", token: "1234" }
56
+ ```
57
+
58
+ ##### Merging non-Hash output, inferring the key from the step name
59
+
60
+ ```ruby
61
+ merge :user
62
+
63
+ # Input: { id: 42 }
64
+ def user(id:, **)
65
+ User.find(id)
66
+ end
67
+ # Output: { id: 42, user: #<User id:42> }
68
+ ```
69
+
70
+ ##### Merging non-Hash output, specifying the key explicitly
71
+
72
+ ```ruby
73
+ merge :find_user, as: :current_user
74
+
75
+ # Input: { id: 42 }
76
+ def find_user(id:, **)
77
+ User.find(id)
78
+ end
79
+ # Output: { id: 42, current_user: #<User id:42> }
80
+ ```
81
+
82
+ #### `tap`
83
+
84
+ A step that mimics Ruby's builtin
85
+ [Kernel#tap](https://ruby-doc.org/3.1.2/Kernel.html#method-i-tap) method. If
86
+ the step succeeds, the step output is ignored and the original input is
87
+ returned. However, if the step fails, then that Failure is returned instead.
88
+
89
+ ```ruby
90
+ tap :track_user
91
+ map :next_step
92
+
93
+ def track_user(user)
94
+ response = Tracker.track(user_id: user.email)
95
+ return Failure(response.body) if response.status >= 400
96
+ end
97
+
98
+ def next_step(user)
99
+ # Normally, the return value if the previous step would be passed
100
+ # as the input to this step. In this case, we don't care, we want
101
+ # to keep going with the original input `user`.
102
+ end
103
+ ```
104
+
105
+ #### `use`
106
+
107
+ Invokes another Transaction (or anything else `#call`-able), and merges the
108
+ result. It can also lookup the item to invoke in a container, which allows it
109
+ to be changed at runtime, or for tests.
110
+
111
+ The output of the invoked item is merged with the input, following the same
112
+ rules as the [`merge`][#merge] step.
113
+
114
+ This also works well in conjunction with the [Class Callable][#class-callable]
115
+ extension.
116
+
117
+ ```ruby
118
+ use FindUser
119
+ use AppContainer, :find_user
120
+ use ->(id:, **) { User.find(id) }, as: "user"
121
+ ```
122
+
123
+ *Note*: The Container-lookup form of this is functionally equivalent to the built-in Dry Container Dependency Inject that is a part of Dry-Transaction (but lacking the `merge` semantics. However, you may find this method to be more readable, particularly when combined with other step adapters with a similar structure.
124
+
125
+ ```ruby
126
+ class CreateUser
127
+ step :validate, with: "validate"
128
+ step :create, with: "create"
129
+
130
+ # vs
131
+
132
+ use UserContainer, "validate"
133
+ use UserContainer, "create"
134
+ end
135
+ ```
136
+
137
+ #### `valid`
138
+
139
+ Runs a Dry::Schema or Dry::Validation::Contract, either passed to the step
140
+ directly, or returned from the step method. It runs the validator on the input
141
+ arguments, and returns Success on the validator output, or the Failure with
142
+ errors returned from the validator.
143
+
144
+ ```ruby
145
+ valid :validate_params
146
+
147
+ def validate_params(params)
148
+ Dry::Schema.Params do
149
+ required(:name).filled(:string)
150
+ required(:email).filled(:string)
151
+ end
152
+ end
153
+ ```
154
+
155
+ *This is essentially equivalent to:*
156
+
157
+ ```
158
+ step :validate_params
159
+
160
+ def validate_params(params)
161
+ Dry::Schema.Params do
162
+ required(:name).filled(:string)
163
+ required(:email).filled(:string)
164
+ end.call(params).to_monad
165
+ end
166
+ ```
167
+
168
+ You can also define the Schema/Contract elsewhere if you want to reuse it, and invoke it:
169
+
170
+ ```
171
+ valid ParamsValidator
172
+ ```
173
+
174
+ #### `maybe`
175
+
176
+ Maybe combines the [`use`][#use] step with the [Validation
177
+ extension][#validation]. Before attempting to run the provided transaction, it
178
+ first runs its defined validator. If that validation passes, then it invokes
179
+ the transaction. If the validation fails, however, then the transaction
180
+ continues on, silently ignoring the failure. This is useful in several
181
+ scenarios, like not running if there's insufficient data, or they've already
182
+ been run.
183
+
184
+ For example, when creating a user, if they provided an email address, we want
185
+ to send a verification email. If they didn't provide an email, or we've already
186
+ verified it, then we can skip that part. Given a `VerifyEmail` transaction with
187
+ a `validation` block that requires an email address, and does something to
188
+ check if we've already verified it, we can use a `maybe` to invoke it. If that
189
+ validator fails, then we can ignore it and create the user anyway.
190
+
191
+ ```ruby
192
+ class VerifyEmail
193
+ include Dry::Transaction
194
+ include Dry::Transaction::Extra
195
+ load_extensions :validation, :class_callable
196
+
197
+ validate do
198
+ params do
199
+ required(:email).filled(type?: EmailAddress)
200
+ end
201
+
202
+ rule(:email) do
203
+ !EmailValidation.exists?(value)
204
+ end
205
+ end
206
+
207
+ step :send_verification_email
208
+ end
209
+
210
+ class CreateUser
211
+ include Dry::Transaction
212
+ include Dry::Transaction::Extra
213
+ load_extensions :validation
214
+
215
+ validate do
216
+ params do
217
+ optional(:email).filled(:string)
218
+ end
219
+ end
220
+
221
+ maybe VerifyEmail
222
+ step :create_user
223
+ ```
224
+
225
+
226
+ ### Extensions
227
+
228
+ #### Validation
229
+
230
+ In addition to the [valid][#valid] step adapter, Dry::Transaction::Extra has
231
+ support for an explicit "pre-flight" validation that runs as the first step.
232
+
233
+ ```ruby
234
+ class CreateUser
235
+ include Dry::Transaction
236
+ include Dry::Transaction::Extra
237
+ load_extensions :validation
238
+
239
+ validate do
240
+ params do
241
+ required(:name).filled(:string)
242
+ optional(:email).maybe(:string)
243
+ end
244
+ end
245
+
246
+ step :create_user
247
+ end
248
+ ```
249
+
250
+ This is useful if you want to, for example, run the transaction as an async background job, but want to first verify the arguments to the job before enqueueing it. If the job is going to fail anyway, why bother creating it in the first place?
251
+
252
+ ```ruby
253
+ result = CreateUser.validator.new.call(params)
254
+ CreateUserJob.perform_async(params) unless result.failure?
255
+ ```
256
+
257
+ #### Class Callable
258
+
259
+ This is a nice shorthand to initialize and call a Transaction in a single method. If you don't need to pass any arguments to the initializer, then you can `#call` it directly on the class:
260
+
261
+ ```ruby
262
+ MyTransaction.new.call(args)
263
+ MyTransaction.call(args)
264
+ ```
265
+
266
+ This is particularly useful when invoking transactions via the [`use`][#use] and [`maybe`][#maybe] steps:
267
+
268
+ ```
269
+ use MyTransaction
270
+ maybe MyOptionalTransaction
271
+ ```
272
+
273
+ ## Development
274
+
275
+ 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.
276
+
277
+ 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).
278
+
279
+ ## Contributing
280
+
281
+ Bug reports and pull requests are welcome on GitHub at https://github.com/paul/dry-transaction-extra. 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/paul/dry-transaction-extra/blob/main/CODE_OF_CONDUCT.md).
282
+
283
+ ## License
284
+
285
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
286
+
287
+ ## Code of Conduct
288
+
289
+ Everyone interacting in the Dry::Transaction::Extra project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/paul/dry-transaction-extra/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/dry/transaction/extra/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "dry-transaction-extra"
7
+ spec.version = Dry::Transaction::Extra::VERSION
8
+ spec.authors = ["Paul Sadauskas"]
9
+ spec.email = ["psadauskas@gmail.com"]
10
+
11
+ spec.summary = "Extra steps and functionality for Dry::Transaction"
12
+ spec.description = "Dry::Transaction comes with a limited set of steps. This \
13
+ gem defines a few more steps that are useful for getting the most out of Transactions."
14
+ spec.homepage = "https://github.com/paul/dry-transaction-extra"
15
+ spec.license = "MIT"
16
+ spec.required_ruby_version = ">= 3.0.0"
17
+
18
+ # spec.metadata["allowed_push_host"] = "TODO: Set to your gem server 'https://example.com'"
19
+
20
+ spec.metadata["homepage_uri"] = spec.homepage
21
+ spec.metadata["source_code_uri"] = "https://github.com/paul/dry-transaction-extra"
22
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
23
+
24
+ # Specify which files should be added to the gem when it is released.
25
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
26
+ spec.files = Dir.chdir(__dir__) do
27
+ `git ls-files -z`.split("\x0").reject do |f|
28
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|circleci)|appveyor)})
29
+ end
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ spec.add_dependency "dry-monads", "~> 1.3"
36
+ spec.add_dependency "dry-transaction", "~> 0.15"
37
+
38
+ spec.add_development_dependency "dry-container", "~> 0.7"
39
+ spec.add_development_dependency "dry-schema", "~> 1.10"
40
+ spec.add_development_dependency "dry-validation", "~> 1.8"
41
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ module Transaction
5
+ module Extra
6
+ # Creates a class-level call method, which creates a new instance and
7
+ # invokes #call on it, delegating all arguments.
8
+ #
9
+ # These are equivalent:
10
+ #
11
+ # MyTransaction.new.call(id: 1234)
12
+ # MyTransaction.call(id: 1234)
13
+ #
14
+ # Note that if you need to pass arguments to the initializer, you can't
15
+ # use this, but if you don't, then this is a nice shortcut.
16
+ #
17
+ module ClassCallable
18
+ def call(...)
19
+ new.call(...)
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ module Transaction
5
+ module Extra
6
+ module Steps
7
+ module Maybe
8
+ module DSL
9
+ class NoValidatorError < ArgumentError
10
+ def initialize(txn)
11
+ super "The object provided to the step (#{txn}) does not implement a `validator` method."
12
+ end
13
+ end
14
+
15
+ # Just like the `use` step, this invokes another transaction.
16
+ # However, it first checks to see if the transaction implements a
17
+ # `validator` method (usually provided by the validation_dsl
18
+ # extension), and if so, will call it before invoking the
19
+ # transaction.
20
+ #
21
+ # If the validation succeeds, then it invokes the transaction as
22
+ # normal. If it fails, it continues on with the next step, passing
23
+ # the original input through.
24
+ #
25
+ # @example
26
+ #
27
+ # step :create_user
28
+ # maybe VerifyEmail
29
+ #
30
+ def maybe(txn_or_container, key = nil, as: nil)
31
+ if key
32
+ container = txn_or_container
33
+ method_name = as || "#{container.name}.#{key}".to_sym
34
+ else
35
+ txn = txn_or_container
36
+ method_name = as || txn.name.to_sym
37
+ end
38
+
39
+ merge(method_name, as:)
40
+ define_method method_name do |*args|
41
+ txn = container[key] if key
42
+ raise NoValidatorError, txn unless txn.respond_to? :validator
43
+
44
+ result = txn.validator.new.call(*args).to_monad
45
+ result.bind { txn.call(*args) }
46
+ .or { Success(*args) }
47
+ end
48
+ rescue NoMethodError => e
49
+ raise e unless e.name == :name
50
+
51
+ raise ArgumentError, "unable to determine step name from #{key_or_container}.\
52
+ Pass an explicit step name using `as:` keyword argument."
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ module Transaction
5
+ module Extra
6
+ module Steps
7
+ # If you're using keyword args as the arguments to your steps, you
8
+ # often want a step to add its output to those args, while keeping the
9
+ # original kwargs intact.
10
+ #
11
+ # * If the output of the step is a Hash, then that hash is merged into the input.
12
+ # * If the output of the step is not a Hash, then a key is inferred
13
+ # from the step name. The name of the key can be overridden with the
14
+ # `as:` option.
15
+ #
16
+ # @option as [Symbol] When merging the output, use this as the key
17
+ #
18
+ # @example Merging Hash output
19
+ #
20
+ # merge :add_context
21
+ #
22
+ # # Input: { user: #<User id:42>, account: #<Account id:1> }
23
+ # def add_context(user:, **)
24
+ # {
25
+ # email: user.email,
26
+ # token: UserToken.lookup(user)
27
+ # }
28
+ # end
29
+ # # Output: { user: #<User id:42>,
30
+ # account: #<Account id:1>,
31
+ # email: "paul@myapp.example",
32
+ # token: "1234" }
33
+ #
34
+ # @example Merging non-Hash output, inferring the key from the step name
35
+ #
36
+ # merge :user
37
+ #
38
+ # # Input: { id: 42 }
39
+ # def user(id:, **)
40
+ # User.find(id)
41
+ # end
42
+ # # Output: { id: 42, user: #<User id:42> }
43
+ #
44
+ # @example Merging non-Hash output, specifying the key explicitly
45
+ #
46
+ # merge :find_user, as: :current_user
47
+ #
48
+ # # Input: { id: 42 }
49
+ # def find_user(id:, **)
50
+ # User.find(id)
51
+ # end
52
+ # # Output: { id: 42, current_user: #<User id:42> }
53
+ #
54
+ class Merge
55
+ include Dry::Monads[:result]
56
+
57
+ def call(operation, options, args)
58
+ if args.size > 1 || (!args[0].is_a?(Hash) && !args[0].nil?)
59
+ raise ArgumentError,
60
+ "the merge step only works with keyword arguments"
61
+ end
62
+
63
+ result = operation.call(*args)
64
+ return result if result.is_a?(Failure)
65
+
66
+ value = result.is_a?(Success) ? result.value! : result
67
+ unless value.is_a?(Hash)
68
+ key = options[:as] || options[:step_name]
69
+ value = { key.to_sym => value }
70
+ end
71
+
72
+ Success((args[0] || {}).merge(value))
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ module Transaction
5
+ module Extra
6
+ module Steps
7
+ # A step that mimics Ruby's builtin
8
+ # [Kernel#tap](https://ruby-doc.org/3.1.2/Kernel.html#method-i-tap)
9
+ # method. If the step succeeds, the step output is ignored and the
10
+ # original input is returned. However, if the step fails, then that
11
+ # Failure is returned instead.
12
+ #
13
+ # @example
14
+ #
15
+ # tap :track_user
16
+ # map :next_step
17
+ #
18
+ # def track_user(user)
19
+ # response = Tracker.track(user_id: user.email)
20
+ # return Failure(response.body) if response.status >= 400
21
+ # end
22
+ #
23
+ # def next_step(user)
24
+ # # Normally, the return value if the previous step would be passed
25
+ # # as the input to this step. In this case, we don't care, we want
26
+ # # to keep going with the original input `user`.
27
+ # end
28
+ class Tap
29
+ include Dry::Monads[:result]
30
+
31
+ def call(operation, _options, args)
32
+ result = operation.call(*args)
33
+ return result if result.is_a?(Failure)
34
+
35
+ Success(*args)
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ module Transaction
5
+ module Extra
6
+ module Steps
7
+ module Use
8
+ module DSL
9
+ # Invokes another transaction, or anything else #callable. Result
10
+ # is merged, according to the same rules as the +merge+ step.
11
+ #
12
+ # Alternatively accepts a Contaner, and a key registered within
13
+ # that container. This allows you to declare the transaction to be
14
+ # used at runtime, instead of file load time.
15
+ #
16
+ # Note that this is basically equivalent to injecting the step into
17
+ # the initializer, or passing in a container. However, using this
18
+ # method may result in more readable code, and less surprise. See
19
+ # README for a more detailed discussion.
20
+ #
21
+ # @param txn_or_container [#call, Dry::Container] A callable, or a Container
22
+ # @param key [Symbol] If provided a Container, use this key for lookup
23
+ #
24
+ # @option as [Symbol] When merging the output, use this as the key
25
+ #
26
+ # @example
27
+ #
28
+ # use FindUser.new
29
+ # use FindUser # When using :class_callable extension
30
+ #
31
+ # @example Find transaction in Container
32
+ #
33
+ # use UserContainer, :find
34
+ #
35
+ # @example Merging output using specified key
36
+ #
37
+ # use FindUser, as: "user"
38
+ #
39
+ # # => { user: #<User: id=1> }
40
+ #
41
+ def use(txn_or_container, key = nil, as: nil)
42
+ if key
43
+ container = txn_or_container
44
+ method_name = as || "#{container.name}.#{key}".to_sym
45
+ else
46
+ txn = txn_or_container
47
+ method_name = as || txn.name.to_sym
48
+ end
49
+
50
+ merge(method_name, as:)
51
+ define_method method_name do |*args|
52
+ txn = container[key] if key
53
+ txn.call(*args)
54
+ end
55
+ rescue NoMethodError => e
56
+ raise e unless e.name == :name
57
+
58
+ raise ArgumentError, "unable to determine step name from #{key_or_container}.\
59
+ Pass an explicit step name using `as:` keyword argument."
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ module Transaction
5
+ module Extra
6
+ module Steps
7
+ # Runs a dry-schema or dry-validation Contract, either passed to the
8
+ # step directly, or returned from the step method. It runs the
9
+ # validator on the input arguments, and returns Success on the
10
+ # validator output, or the Failure with errors returned from the
11
+ # validator.
12
+ #
13
+ # @example Validator defined in step implementation
14
+ #
15
+ # valid :validate_params
16
+ #
17
+ # def validate_params(params)
18
+ # Dry::Schema.Params do
19
+ # required(:name).filled(:string)
20
+ # required(:email).filled(:string)
21
+ # end
22
+ # end
23
+ #
24
+ # This is essentially equivalent to:
25
+ #
26
+ # step :validate_params
27
+ #
28
+ # def validate_params(params)
29
+ # Dry::Schema.Params do
30
+ # required(:name).filled(:string)
31
+ # required(:email).filled(:string)
32
+ # end.call(params).to_monad
33
+ # end
34
+ #
35
+ #
36
+ # @example Validator provided to the step
37
+ #
38
+ # valid ParamsValidator
39
+ #
40
+ class Valid
41
+ include Dry::Monads[:result]
42
+ def call(operation, _options, args)
43
+ if args.size > 1 || (!args[0].is_a?(Hash) && !args[0].nil?)
44
+ raise ArgumentError,
45
+ "the valid step only works with hash/keyword arguments"
46
+ end
47
+
48
+ # The operation is a callable that returns a schema/contract, which
49
+ # itself needs to be called
50
+ result = operation.call.call(args[0])
51
+ if result.success?
52
+ Success(result.to_h)
53
+ else
54
+ Failure(result)
55
+ end
56
+ end
57
+
58
+ module DSL
59
+ def valid(validator, name: nil)
60
+ return super(validator) if validator.is_a?(Symbol)
61
+
62
+ method_name = (name || validator.inspect || "validate").to_sym
63
+ define_method method_name do |**|
64
+ validator
65
+ end
66
+
67
+ super(method_name)
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ module Transaction
5
+ module Extra
6
+ module ValidationDSL
7
+ def self.extended(klass)
8
+ klass.extend Dry::Core::ClassAttributes
9
+ # The Dry::Validation Contract to run as the first step in the
10
+ # Transaction. This exposes it publicly, so you can run it outside
11
+ # the context of the Transction. This is useful if, for example, you
12
+ # want to run the transaction in a job, but want to check if the
13
+ # arguments are valid before enqueueing the job.
14
+ #
15
+ # @example
16
+ #
17
+ # class MyTransaction
18
+ # validate do
19
+ # params do
20
+ # required(:name).filled(:string)
21
+ # end
22
+ # end
23
+ # end
24
+ #
25
+ # MyTransaction.validator.new.call(name: "Jane")
26
+ # # => #<Dry::Validation::Result{name: "Jane"} errors={}>
27
+ klass.defines :validator
28
+
29
+ require "dry/validation"
30
+ Dry::Validation.load_extensions(:monads)
31
+ end
32
+
33
+ # Allows you to declare a class-level validator, and run it as the
34
+ # first step of the Transaction.
35
+ #
36
+ # @example Define the validation inline
37
+ #
38
+ # class CreateUser
39
+ # include Dry::Transaction
40
+ # include Dry::Transaction::Extra
41
+ # load_extensions :validation
42
+ #
43
+ # validate do
44
+ # params do
45
+ # required(:name).filled(:string)
46
+ # optional(:email).maybe(:string)
47
+ # end
48
+ # end
49
+ # end
50
+ #
51
+ # @example Reference a Validation defined elsewhere
52
+ #
53
+ # class NewUserContract < Dry::Validation::Contract
54
+ # params do
55
+ # required(:name).filled(:string)
56
+ # optional(:email).maybe(:string)
57
+ # end
58
+ # end
59
+ #
60
+ # class CreateUser
61
+ # include Dry::Transaction
62
+ # include Dry::Transaction::Extra
63
+ # load_extensions :validation
64
+ #
65
+ # validate NewUserContract
66
+ # end
67
+ #
68
+ def validate(contract = nil, &block)
69
+ validator(contract || Class.new(Dry::Validation::Contract, &block))
70
+
71
+ valid(validator.new, name: "validate")
72
+ end
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dry
4
+ module Transaction
5
+ module Extra
6
+ VERSION = "0.1.0"
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "extra/version"
4
+
5
+ require "dry/monads"
6
+ require "dry/transaction"
7
+
8
+ require_relative "extra/steps/tap"
9
+ require_relative "extra/steps/maybe"
10
+ require_relative "extra/steps/merge"
11
+ require_relative "extra/steps/use"
12
+ require_relative "extra/steps/valid"
13
+
14
+ require_relative "extra/class_callable"
15
+ require_relative "extra/validation_dsl"
16
+
17
+ module Dry
18
+ module Transaction
19
+ module Extra
20
+ def self.included(klass)
21
+ klass.extend Extra::Steps::Maybe::DSL
22
+ klass.extend Extra::Steps::Use::DSL
23
+ klass.extend Extra::Steps::Valid::DSL
24
+
25
+ klass.extend Dry::Core::Extensions
26
+
27
+ klass.register_extension :validation do
28
+ klass.extend ValidationDSL
29
+ end
30
+
31
+ klass.register_extension :class_callable do
32
+ klass.extend ClassCallable
33
+ end
34
+ end
35
+
36
+ adapters = Dry::Transaction::StepAdapters
37
+ {
38
+ merge: Extra::Steps::Merge.new,
39
+ tap: Extra::Steps::Tap.new,
40
+ valid: Extra::Steps::Valid.new
41
+ }.each do |key, impl|
42
+ adapters.register(key, impl) unless adapters.key?(key)
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,8 @@
1
+ module Dry
2
+ module Transaction
3
+ module Extra
4
+ VERSION: String
5
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
6
+ end
7
+ end
8
+ end
metadata ADDED
@@ -0,0 +1,135 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dry-transaction-extra
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Paul Sadauskas
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-01-24 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: dry-monads
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.3'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.3'
27
+ - !ruby/object:Gem::Dependency
28
+ name: dry-transaction
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.15'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.15'
41
+ - !ruby/object:Gem::Dependency
42
+ name: dry-container
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '0.7'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '0.7'
55
+ - !ruby/object:Gem::Dependency
56
+ name: dry-schema
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.10'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.10'
69
+ - !ruby/object:Gem::Dependency
70
+ name: dry-validation
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '1.8'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '1.8'
83
+ description: Dry::Transaction comes with a limited set of steps. This gem defines
84
+ a few more steps that are useful for getting the most out of Transactions.
85
+ email:
86
+ - psadauskas@gmail.com
87
+ executables: []
88
+ extensions: []
89
+ extra_rdoc_files: []
90
+ files:
91
+ - ".rspec"
92
+ - ".rubocop.yml"
93
+ - CODE_OF_CONDUCT.md
94
+ - Gemfile
95
+ - Gemfile.lock
96
+ - LICENSE.txt
97
+ - README.md
98
+ - Rakefile
99
+ - dry-transaction-extra.gemspec
100
+ - lib/dry/transaction/extra.rb
101
+ - lib/dry/transaction/extra/class_callable.rb
102
+ - lib/dry/transaction/extra/steps/maybe.rb
103
+ - lib/dry/transaction/extra/steps/merge.rb
104
+ - lib/dry/transaction/extra/steps/tap.rb
105
+ - lib/dry/transaction/extra/steps/use.rb
106
+ - lib/dry/transaction/extra/steps/valid.rb
107
+ - lib/dry/transaction/extra/validation_dsl.rb
108
+ - lib/dry/transaction/extra/version.rb
109
+ - sig/dry/transaction/extra.rbs
110
+ homepage: https://github.com/paul/dry-transaction-extra
111
+ licenses:
112
+ - MIT
113
+ metadata:
114
+ homepage_uri: https://github.com/paul/dry-transaction-extra
115
+ source_code_uri: https://github.com/paul/dry-transaction-extra
116
+ post_install_message:
117
+ rdoc_options: []
118
+ require_paths:
119
+ - lib
120
+ required_ruby_version: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: 3.0.0
125
+ required_rubygems_version: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - ">="
128
+ - !ruby/object:Gem::Version
129
+ version: '0'
130
+ requirements: []
131
+ rubygems_version: 3.4.1
132
+ signing_key:
133
+ specification_version: 4
134
+ summary: Extra steps and functionality for Dry::Transaction
135
+ test_files: []