dry-transaction-extraaa 0.1.2

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: 8fc34accf055a9c15faa248a168c8833ee685f34ceb5c098e6e15afb704310cb
4
+ data.tar.gz: 3dacc5b67d5de8ccf658e569354fdd3e899c177bff8d2f55333b011704452041
5
+ SHA512:
6
+ metadata.gz: e78b87c994c9623aade8329c2d68b808d0dff7ceafa96f976cd5172a799d80d5c91c535d283293c192bc8b45bbbc973b920c498d6e499336fb5d5f8ac8935615
7
+ data.tar.gz: 493d22d67fca734ae4216555d86be603e76108efd8b1c123fe53ec9ddd95b3b45547058b2cd581181645a42172fbf5c63bdd65a4afbb44a2b19bf294932576d5
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,36 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.2
3
+ NewCops: enable
4
+
5
+ Layout/LineLength:
6
+ Max: 120
7
+
8
+ Lint/AmbiguousBlockAssociation:
9
+ Exclude:
10
+ - "spec/**/*" # `expect { }.to change { }` is fine
11
+
12
+ Metrics/BlockLength:
13
+ Exclude:
14
+ - Gemfile
15
+ - Guardfile
16
+ AllowedMethods:
17
+ - configure
18
+ - context
19
+ - define
20
+ - describe
21
+ - factory
22
+ - it
23
+ - namespace
24
+ - specify
25
+ - task
26
+ - shared_examples_for
27
+ - shared_context
28
+ - feature
29
+
30
+ Style/StringLiterals:
31
+ Enabled: true
32
+ EnforcedStyle: double_quotes
33
+
34
+ Style/StringLiteralsInInterpolation:
35
+ Enabled: true
36
+ 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-extraaa.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,296 @@
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-extraaa
11
+
12
+ If bundler is not being used to manage dependencies, install the gem by executing:
13
+
14
+ $ gem install dry-transaction-extraaa
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-extraaa"
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
29
+ used with keyword arguments.
30
+ * [tap](#tap) -- Similar to Ruby `Kernel#tap`, discards the return value of the step
31
+ and returns the original input. If the step fails, then returns the Failure
32
+ instead.
33
+ * [valid](#valid) -- Runs a Dry::Schema or Dry::Validation::Contract on the
34
+ input, and transforms the validation Result to a Result monad.
35
+ * [use](#use) -- Invokes another transaction (or any other callable), and
36
+ merges the result.
37
+ * [maybe](#maybe) -- Optionally invokes another transaction by first
38
+ attempting to invoke the validator. If the validation fails, it continues to
39
+ the next step without failing.
40
+
41
+ #### `merge`
42
+
43
+ If you're using keyword args as the arguments to your steps, you often want a
44
+ step to add its output to those args, while keeping the original kwargs intact.
45
+
46
+ * If the output of the step is a Hash, then that hash is merged into the input.
47
+ * If the output of the step is not a Hash, then a key is inferred from the
48
+ step name. The name of the key can be overridden with the `as:` option.
49
+
50
+ ##### Merging Hash output
51
+
52
+ ```ruby
53
+ merge :add_context
54
+
55
+ # Input: { user: #<User id:42>, account: #<Account id:1> }
56
+ def add_context(user:, **)
57
+ {
58
+ email: user.email,
59
+ token: UserToken.lookup(user)
60
+ }
61
+ end
62
+ # Output: { user: #<User id:42>, account: #<Account id:1>, email: "paul@myapp.example", token: "1234" }
63
+ ```
64
+
65
+ ##### Merging non-Hash output, inferring the key from the step name
66
+
67
+ ```ruby
68
+ merge :user
69
+
70
+ # Input: { id: 42 }
71
+ def user(id:, **)
72
+ User.find(id)
73
+ end
74
+ # Output: { id: 42, user: #<User id:42> }
75
+ ```
76
+
77
+ ##### Merging non-Hash output, specifying the key explicitly
78
+
79
+ ```ruby
80
+ merge :find_user, as: :current_user
81
+
82
+ # Input: { id: 42 }
83
+ def find_user(id:, **)
84
+ User.find(id)
85
+ end
86
+ # Output: { id: 42, current_user: #<User id:42> }
87
+ ```
88
+
89
+ #### `tap`
90
+
91
+ A step that mimics Ruby's builtin
92
+ [Kernel#tap](https://ruby-doc.org/3.1.2/Kernel.html#method-i-tap) method. If
93
+ the step succeeds, the step output is ignored and the original input is
94
+ returned. However, if the step fails, then that Failure is returned instead.
95
+
96
+ ```ruby
97
+ tap :track_user
98
+ map :next_step
99
+
100
+ def track_user(user)
101
+ response = Tracker.track(user_id: user.email)
102
+ return Failure(response.body) if response.status >= 400
103
+ end
104
+
105
+ def next_step(user)
106
+ # Normally, the return value if the previous step would be passed
107
+ # as the input to this step. In this case, we don't care, we want
108
+ # to keep going with the original input `user`.
109
+ end
110
+ ```
111
+
112
+ #### `use`
113
+
114
+ Invokes another Transaction (or anything else `#call`-able), and merges the
115
+ result. It can also lookup the item to invoke in a container, which allows it
116
+ to be changed at runtime, or for tests.
117
+
118
+ The output of the invoked item is merged with the input, following the same
119
+ rules as the [`merge`][#merge] step.
120
+
121
+ This also works well in conjunction with the [Class Callable][#class-callable]
122
+ extension.
123
+
124
+ ```ruby
125
+ use FindUser
126
+ use AppContainer, :find_user
127
+ use ->(id:, **) { User.find(id) }, as: "user"
128
+ ```
129
+
130
+ *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.
131
+
132
+ ```ruby
133
+ class CreateUser
134
+ step :validate, with: "validate"
135
+ step :create, with: "create"
136
+
137
+ # vs
138
+
139
+ use UserContainer, "validate"
140
+ use UserContainer, "create"
141
+ end
142
+ ```
143
+
144
+ #### `valid`
145
+
146
+ Runs a Dry::Schema or Dry::Validation::Contract, either passed to the step
147
+ directly, or returned from the step method. It runs the validator on the input
148
+ arguments, and returns Success on the validator output, or the Failure with
149
+ errors returned from the validator.
150
+
151
+ ```ruby
152
+ valid :validate_params
153
+
154
+ def validate_params(params)
155
+ Dry::Schema.Params do
156
+ required(:name).filled(:string)
157
+ required(:email).filled(:string)
158
+ end
159
+ end
160
+ ```
161
+
162
+ *This is essentially equivalent to:*
163
+
164
+ ```
165
+ step :validate_params
166
+
167
+ def validate_params(params)
168
+ Dry::Schema.Params do
169
+ required(:name).filled(:string)
170
+ required(:email).filled(:string)
171
+ end.call(params).to_monad
172
+ end
173
+ ```
174
+
175
+ You can also define the Schema/Contract elsewhere if you want to reuse it, and invoke it:
176
+
177
+ ```
178
+ valid ParamsValidator
179
+ ```
180
+
181
+ #### `maybe`
182
+
183
+ Maybe combines the [`use`]( #use ) step with the [Validation
184
+ extension]( #validation ). Before attempting to run the provided transaction, it
185
+ first runs its defined validator. If that validation passes, then it invokes
186
+ the transaction. If the validation fails, however, then the transaction
187
+ continues on, silently ignoring the failure. This is useful in several
188
+ scenarios, like not running if there's insufficient data, or they've already
189
+ been run.
190
+
191
+ For example, when creating a user, if they provided an email address, we want
192
+ to send a verification email. If they didn't provide an email, or we've already
193
+ verified it, then we can skip that part. Given a `VerifyEmail` transaction with
194
+ a `validation` block that requires an email address, and does something to
195
+ check if we've already verified it, we can use a `maybe` to invoke it. If that
196
+ validator fails, then we can ignore it and create the user anyway.
197
+
198
+ ```ruby
199
+ class VerifyEmail
200
+ include Dry::Transaction
201
+ include Dry::Transaction::Extra
202
+ load_extensions :validation, :class_callable
203
+
204
+ validate do
205
+ params do
206
+ required(:email).filled(type?: EmailAddress)
207
+ end
208
+
209
+ rule(:email) do
210
+ !EmailValidation.exists?(value)
211
+ end
212
+ end
213
+
214
+ step :send_verification_email
215
+ end
216
+
217
+ class CreateUser
218
+ include Dry::Transaction
219
+ include Dry::Transaction::Extra
220
+ load_extensions :validation
221
+
222
+ validate do
223
+ params do
224
+ optional(:email).filled(:string)
225
+ end
226
+ end
227
+
228
+ maybe VerifyEmail
229
+ step :create_user
230
+ ```
231
+
232
+
233
+ ### Extensions
234
+
235
+ #### Validation
236
+
237
+ In addition to the [valid]( #valid ) step adapter, Dry::Transaction::Extra has
238
+ support for an explicit "pre-flight" validation that runs as the first step.
239
+
240
+ ```ruby
241
+ class CreateUser
242
+ include Dry::Transaction
243
+ include Dry::Transaction::Extra
244
+ load_extensions :validation
245
+
246
+ validate do
247
+ params do
248
+ required(:name).filled(:string)
249
+ optional(:email).maybe(:string)
250
+ end
251
+ end
252
+
253
+ step :create_user
254
+ end
255
+ ```
256
+
257
+ 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?
258
+
259
+ ```ruby
260
+ result = CreateUser.validator.new.call(params)
261
+ CreateUserJob.perform_async(params) unless result.failure?
262
+ ```
263
+
264
+ #### Class Callable
265
+
266
+ 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:
267
+
268
+ ```ruby
269
+ MyTransaction.new.call(args)
270
+ MyTransaction.call(args)
271
+ ```
272
+
273
+ This is particularly useful when invoking transactions via the [`use`]( #use ) and [`maybe`]( #maybe ) steps:
274
+
275
+ ```
276
+ use MyTransaction
277
+ maybe MyOptionalTransaction
278
+ ```
279
+
280
+ ## Development
281
+
282
+ 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.
283
+
284
+ 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).
285
+
286
+ ## Contributing
287
+
288
+ Bug reports and pull requests are welcome on GitHub at https://github.com/HouseAccountEng/dry-transaction-extraaa. 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/HouseAccountEng/dry-transaction-extraaa/blob/main/CODE_OF_CONDUCT.md).
289
+
290
+ ## License
291
+
292
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
293
+
294
+ ## Code of Conduct
295
+
296
+ 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/HouseAccountEng/dry-transaction-extraaa/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,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,63 @@
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)
45
+ if result.failure?
46
+ # Rails.logger.debug "Skipping #{txn} because of errors: #{result.errors.to_h}"
47
+ return Success(*args)
48
+ end
49
+
50
+ txn.call(*args)
51
+ end
52
+ rescue NoMethodError => e
53
+ raise e unless e.name == :name
54
+
55
+ raise ArgumentError, "unable to determine step name from #{key_or_container}.\
56
+ Pass an explicit step name using `as:` keyword argument."
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
63
+ 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.2"
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,134 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dry-transaction-extraaa
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ platform: ruby
6
+ authors:
7
+ - Paul Sadauskas
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-04-16 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
+ - lib/dry/transaction/extra.rb
100
+ - lib/dry/transaction/extra/class_callable.rb
101
+ - lib/dry/transaction/extra/steps/maybe.rb
102
+ - lib/dry/transaction/extra/steps/merge.rb
103
+ - lib/dry/transaction/extra/steps/tap.rb
104
+ - lib/dry/transaction/extra/steps/use.rb
105
+ - lib/dry/transaction/extra/steps/valid.rb
106
+ - lib/dry/transaction/extra/validation_dsl.rb
107
+ - lib/dry/transaction/extra/version.rb
108
+ - sig/dry/transaction/extra.rbs
109
+ homepage: https://github.com/HouseAccountEng/dry-transaction-extraaa
110
+ licenses:
111
+ - MIT
112
+ metadata:
113
+ homepage_uri: https://github.com/HouseAccountEng/dry-transaction-extraaa
114
+ source_code_uri: https://github.com/HouseAccountEng/dry-transaction-extraaa
115
+ post_install_message:
116
+ rdoc_options: []
117
+ require_paths:
118
+ - lib
119
+ required_ruby_version: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - ">="
122
+ - !ruby/object:Gem::Version
123
+ version: 3.0.0
124
+ required_rubygems_version: !ruby/object:Gem::Requirement
125
+ requirements:
126
+ - - ">="
127
+ - !ruby/object:Gem::Version
128
+ version: '0'
129
+ requirements: []
130
+ rubygems_version: 3.4.22
131
+ signing_key:
132
+ specification_version: 4
133
+ summary: Extra steps and functionality for Dry::Transaction
134
+ test_files: []