toolx 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +3 -0
  3. data/.rubocop.yml +58 -0
  4. data/CODE_OF_CONDUCT.md +132 -0
  5. data/Guardfile +11 -0
  6. data/LICENSE.txt +21 -0
  7. data/README.md +452 -0
  8. data/Rakefile +12 -0
  9. data/lib/tasks/.keep +0 -0
  10. data/lib/tasks/aliases.rake +50 -0
  11. data/lib/tasks/annotate_rb.rake +23 -0
  12. data/lib/tasks/stateman.rake +50 -0
  13. data/lib/templates/stateman/migration.rb.erb +24 -0
  14. data/lib/templates/stateman/state_machine.rb.erb +37 -0
  15. data/lib/templates/stateman/transition.rb.erb +15 -0
  16. data/lib/toolx/core/concerns/custom_identifier.rb +53 -0
  17. data/lib/toolx/core/concerns/date_time_to_boolean.rb +54 -0
  18. data/lib/toolx/core/concerns/inquirer.rb +89 -0
  19. data/lib/toolx/core/concerns/transformer.rb +41 -0
  20. data/lib/toolx/core/concerns/with_state_machine.rb +49 -0
  21. data/lib/toolx/core/env.rb +45 -0
  22. data/lib/toolx/core/errors/api_error.rb +40 -0
  23. data/lib/toolx/core/errors/app_error.rb +3 -0
  24. data/lib/toolx/core/errors/nested_error.rb +32 -0
  25. data/lib/toolx/core/errors/nested_standard_error.rb +11 -0
  26. data/lib/toolx/core/form.rb +9 -0
  27. data/lib/toolx/core/operation/callbacks_wrapper.rb +27 -0
  28. data/lib/toolx/core/operation/flow.rb +220 -0
  29. data/lib/toolx/core/operation/params_wrapper.rb +33 -0
  30. data/lib/toolx/core/operation/rescue_wrapper.rb +20 -0
  31. data/lib/toolx/core/operation/response_wrapper.rb +34 -0
  32. data/lib/toolx/core/operation/simplified_result.rb +45 -0
  33. data/lib/toolx/core/operation/transaction_wrapper.rb +32 -0
  34. data/lib/toolx/core/operation.rb +27 -0
  35. data/lib/toolx/core/operation_base.rb +4 -0
  36. data/lib/toolx/core/presenter.rb +50 -0
  37. data/lib/toolx/core/simple_crypt.rb +28 -0
  38. data/lib/toolx/version.rb +5 -0
  39. data/lib/toolx.rb +30 -0
  40. data/sig/toolx.rbs +4 -0
  41. metadata +337 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f027d545a91be1a02f8ef28f52ced20c6d6ffe3defc99be3f59dd783b78bed2f
4
+ data.tar.gz: 453e20a3f42da721d4acdb50fb62de95ad62b4801c6c652c3285c8a5de311a21
5
+ SHA512:
6
+ metadata.gz: 9551fd33fe000bf1a10e5500a409f770ea64533b3db892825174f96659773fa93b872b78f21cb7dbdfc575045e54024bddb18e499b96417c36a1edf0a931a3b4
7
+ data.tar.gz: '018ed1cadf76d903502d6e1b5fdd1c3bc14d3891995d35d2566fb36c2c15ffbd59ea04c6af87d46f7c876cbf840a5f903b3b2eae8b6d43e3afafa3738ee74de1'
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format progress
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,58 @@
1
+ # Omakase Ruby styling for Rails
2
+ inherit_gem: { rubocop-rails-omakase: rubocop.yml }
3
+
4
+ # Overwrite or add rules to create your own house style
5
+ #
6
+ # # Use `[a, [b, c]]` not `[ a, [ b, c ] ]`
7
+ # Layout/SpaceInsideArrayLiteralBrackets:
8
+ # Enabled: false
9
+
10
+ AllCops:
11
+ TargetRubyVersion: 3.4.0
12
+ MaxFilesInCache: 30000
13
+ DefaultFormatter: progress
14
+ NewCops: enable
15
+ Exclude:
16
+ - 'spec/fixtures/**/*'
17
+ - 'tmp/**/*'
18
+ - 'bin/*'
19
+ - 'lib/tasks/**/*'
20
+
21
+ Style/AsciiComments:
22
+ Enabled: false
23
+
24
+ Style/ClassAndModuleChildren:
25
+ Enabled: false
26
+
27
+ Style/Documentation:
28
+ Enabled: false
29
+
30
+ Layout/LineLength:
31
+ Max: 240
32
+ IgnoredPatterns:
33
+ - !ruby/regexp /\A +(it|describe|context|shared_examples|include_examples|it_behaves_like|def) ["']/
34
+ Severity: info
35
+
36
+ Layout/EndOfLine:
37
+ EnforcedStyle: lf
38
+
39
+ Metrics/MethodLength:
40
+ Max: 30
41
+
42
+ Metrics/AbcSize:
43
+ Max: 36
44
+
45
+ Layout/HashAlignment:
46
+ Enabled: false
47
+ EnforcedHashRocketStyle: table
48
+ EnforcedColonStyle: table
49
+ EnforcedLastArgumentHashStyle: always_inspect
50
+
51
+ Layout/MultilineMethodCallIndentation:
52
+ Enabled: true
53
+
54
+ Layout/SpaceInsideArrayLiteralBrackets:
55
+ EnforcedStyle: no_space
56
+
57
+ Style/StringLiterals:
58
+ EnforcedStyle: single_quotes
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/Guardfile ADDED
@@ -0,0 +1,11 @@
1
+ guard :rspec, cmd: 'rspec' do
2
+ watch(%r{^lib/(.+).rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
3
+ watch(%r{^spec/(.+).rb$}) { |m| "spec/#{m[1]}.rb" }
4
+ watch('spec/spec_helper.rb') { 'spec' }
5
+ watch('Gemfile')
6
+ end
7
+
8
+ guard :rubocop, all_on_start: false, cli: ['--format', 'clang'] do
9
+ watch(%r{.+\.rb$})
10
+ watch(%r{(?:.+/)?\.rubocop\.yml$}) { |m| File.dirname(m[0]) }
11
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Pawel Niemczyk
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,452 @@
1
+ # Toolx
2
+
3
+ This gem adds a set of tools to enhance your Ruby on Rails application, providing utilities for envs, uniq ids, and more.
4
+
5
+ ## Installation
6
+
7
+ Install the gem and add to the application's Gemfile by executing:
8
+
9
+ $ bundle add toolx
10
+
11
+ Use rake tasks if needed:
12
+
13
+ ```bash
14
+ bin/rails toolx:aliases:generate # Generate toolx_aliases.rb
15
+ bin/rails toolx:annotate:generate # Generate annotate rake tasks
16
+ bin/rails toolx:stateman:generate[model] # Generate StateMachine, Transition class, and migration
17
+ ```
18
+
19
+ Add your toolx mixins to the `ApplicationRecord` or any other model:
20
+
21
+ ```ruby
22
+ class ApplicationRecord < ActiveRecord::Base
23
+ primary_abstract_class
24
+
25
+ include Toolx::Core::Concerns::Inquirer
26
+ include Toolx::Core::Concerns::Transformer
27
+ include Toolx::Core::Concerns::CustomIdentifier
28
+ include Toolx::Core::Concerns::DateTimeToBoolean
29
+ include Toolx::Core::Concerns::WithStateMachine
30
+ end
31
+ ```
32
+
33
+
34
+ ## Features
35
+
36
+ ### Env
37
+
38
+ Access environment variables in a clean, expressive way.
39
+
40
+ ```ruby
41
+ ENV['ROLE'] = 'admin'
42
+
43
+ Env = Toolx::Core::Env
44
+
45
+ Env[:role] # => "admin"
46
+ Env.role # => "admin"
47
+ Env.role_.admin? # => true
48
+ Env.role_.user? # => false
49
+ Env.debug? # => true/false (boolean cast)
50
+ Env.timeout!(10) # => 10 (integer cast)
51
+ Env.role_(:none).none? # => true (inquiry cast)
52
+ ```
53
+
54
+ ### CustomIdentifier
55
+
56
+ Generate a custom ID for the `id` column
57
+
58
+ ```ruby
59
+ CustomIdentifier = Toolx::Core::Concerns::CustomIdentifier
60
+
61
+ class User < ApplicationRecord
62
+ include CustomIdentifier
63
+ cid 'usr'
64
+ end
65
+
66
+ user.id # => "usr_Nc82xL0w92..."
67
+ ```
68
+
69
+ ```ruby
70
+ CustomIdentifier = Toolx::Core::Concerns::CustomIdentifier
71
+
72
+ class Document < ApplicationRecord
73
+ include CustomIdentifier
74
+ belongs_to :workspace
75
+ cid 'doc', related: { workspace: 4 }
76
+ end
77
+
78
+ # If workspace_id = "wsp_ABCXYZ...", then document id will be like:
79
+ # "doc_ABCXabcd123..."
80
+ ```
81
+
82
+ ### Inquirer
83
+
84
+ Adds ? predicate-style behavior for strings.
85
+
86
+ ```ruby
87
+
88
+ class User < ApplicationRecord
89
+ include Toolx::Core::Concerns::Inquirer
90
+
91
+ inquirer :status, :kind
92
+ end
93
+
94
+ user = User.new(status: "active", kind: "admin")
95
+ user.status.active? # => true
96
+ user.status.inactive? # => false
97
+ user.kind.admin? # => true
98
+ user.kind.user? # => false
99
+ ```
100
+
101
+ ### Transformer
102
+
103
+ Transform input strings on assignment (e.g., strip, downcase, etc.)
104
+
105
+ ```ruby
106
+ class User < ApplicationRecord
107
+ include Toolx::Core::Concerns::Transformer
108
+
109
+ transform :email, :strip, :downcase
110
+ transform :name, :strip, :presence
111
+ end
112
+
113
+ user = User.new
114
+ user.email = " Foo@Example.COM "
115
+ user.name = " "
116
+
117
+ user.email # => "foo@example.com"
118
+ user.name # => nil
119
+ ```
120
+
121
+ ### DateTimeToBoolean
122
+
123
+ Use datetime fields as boolean-style flags:
124
+
125
+ ```ruby
126
+ class User < ApplicationRecord
127
+ include Toolx::Core::Concerns::DateTimeToBoolean
128
+
129
+ date_time_to_boolean :deleted_at
130
+ end
131
+
132
+ user.deleted? # => false
133
+ user.deleted! # sets deleted_at to current time
134
+ user.deleted = true # also sets current time
135
+ user.deleted = false # sets deleted_at to nil
136
+ ```
137
+
138
+ ### Errors
139
+
140
+ A structured, extensible error-handling framework:
141
+
142
+
143
+ Wrap errors with nested backtrace info
144
+
145
+ ```ruby
146
+ class MyError < StandardError
147
+ include Toolx::Core::Errors::NestedError
148
+ end
149
+
150
+ begin
151
+ raise "Something failed"
152
+ rescue => e
153
+ raise MyError.new("Outer error", e)
154
+ end
155
+ ```
156
+
157
+ Base error classes
158
+
159
+ ```ruby
160
+ Toolx::Core::Errors::NestedStandardError
161
+ Toolx::Core::Errors::AppError
162
+ Toolx::Core::Errors::ApiError
163
+
164
+ Toolx::Core::Errors::BadRequest
165
+ Toolx::Core::Errors::Unauthorized
166
+ Toolx::Core::Errors::NotFound
167
+ Toolx::Core::Errors::Conflict
168
+ Toolx::Core::Errors::UnprocessableEntity
169
+ Toolx::Core::Errors::FailedDependency
170
+ Toolx::Core::Errors::Forbidden
171
+ Toolx::Core::Errors::InternalServerError
172
+ Toolx::Core::Errors::BadGateway
173
+ Toolx::Core::Errors::ServiceUnavailable
174
+ Toolx::Core::Errors::GatewayTimeout
175
+ ```
176
+
177
+ ### Form
178
+
179
+ A simple form builder for Rails applications:
180
+
181
+ ```ruby
182
+ class Space::InfoForm < Toolx::Core::Form
183
+ attribute :name, :string
184
+ attribute :description, :string
185
+ attribute :kind, :string
186
+
187
+ validates :name, presence: true
188
+ validates :kind, inclusion: { in: Space::KINDS }, allow_blank: true
189
+ end
190
+ ```
191
+
192
+ ### Presenter
193
+
194
+ Elegant presenter base class wrapping any object, with I18n support and flexible invocation patterns.
195
+
196
+ ```ruby
197
+ class UserPresenter < Toolx::Core::Presenter
198
+ def display_name
199
+ name.upcase
200
+ end
201
+ end
202
+
203
+ UserPresenter.present(user).display_name # => "ALICE"
204
+ ```
205
+
206
+ to_proc usage
207
+
208
+ ```ruby
209
+ users.map(&UserPresenter) # => wraps each user
210
+ ```
211
+
212
+ as_proc(use: :method) usage
213
+
214
+ ```ruby
215
+ users.map(&UserPresenter.as_proc(use: :display_name))
216
+ ```
217
+
218
+ auto_present detection
219
+
220
+ ```ruby
221
+ class Article
222
+ class Presenter < ::Toolx::Core::Presenter
223
+ def short_title = title.truncate(10)
224
+ end
225
+ end
226
+
227
+ Presenter.auto_present(Article.new(title: "A very long title"))
228
+ ```
229
+
230
+
231
+ ### SimpleCrypt
232
+
233
+ Simple AES encryption helper using ActiveSupport::MessageEncryptor.
234
+
235
+ ```ruby
236
+ Toolx::Core::SimpleCrypt.encrypt('hello') # => encrypted string
237
+ Toolx::Core::SimpleCrypt.decrypt(encrypted_string) # => "hello"
238
+ ```
239
+
240
+ * Uses ENV['CRYPT_SECRET'] or Rails credentials by default.
241
+ * You can pass a custom secret: if needed.
242
+
243
+ ```ruby
244
+ encrypted = Toolx::Core::SimpleCrypt.encrypt('secret info', secret: 'a' * 32)
245
+ Toolx::Core::SimpleCrypt.decrypt(encrypted, secret: 'a' * 32) # => 'secret info'
246
+ ```
247
+
248
+ ❗️ Errors
249
+ * MissingSecretError – when no secret is configured
250
+ * EncryptionError – on encryption failure
251
+ * DecryptionError – on verification or decoding failure
252
+
253
+ ### Operation
254
+
255
+ A base class for service operations, providing a structured way to define and execute business logic with typed parameters and responses.
256
+
257
+ ```ruby
258
+ class Country::Code < Toolx::Core::Operation
259
+ self.transactional = false # When we do not need transaction support, by default it is true
260
+ simplified_result :value
261
+
262
+ params { attribute :source, Types.Instance(ISO3166::Country) | Types::Coercible::String }
263
+ response { attribute :value, Types::Symbol }
264
+
265
+ def perform = { value: Country::Object[source:].alpha2.to_sym }
266
+
267
+ private
268
+
269
+ delegate :source, to: :params
270
+ end
271
+ # when simplified_result is used it is possible to use it like this:
272
+ source = 'Polska'
273
+ Country::Code[source:] # => :PL
274
+ Country::Code.call(source:) # => :PL
275
+ Country::Code.(source:) # => :PL
276
+ # And default one
277
+ Country::Code.new(source:).perform.value # => :PL
278
+ ```
279
+
280
+ Operation provides accessories like `params`, `response` but it can be used as Param and Response classes as well.
281
+
282
+ ```ruby
283
+ class Country::Code < Toolx::Core::Operation
284
+ self.transactional = false # When we do not need transaction support
285
+ # callback :before, :after, :around, etc. can be used to add hooks
286
+ after -> { 'send notification' }
287
+ before :validate!
288
+
289
+ rescue_from ActiveRecord::RecordInvalid, with: :raise_something
290
+
291
+ class Params
292
+ attribute :source, Types.Instance(ISO3166::Country) | Types::Coercible::String }
293
+ end
294
+
295
+ class Response
296
+ attribute :value, Types::Symbol
297
+ end
298
+
299
+ def perform = { value: Country::Object[source:].alpha2.to_sym }
300
+
301
+ private
302
+
303
+ def validate! = true
304
+
305
+ def raise_something(exception)
306
+ raise Toolx::Core::Errors::BadRequest, "Invalid source: #{exception.message}"
307
+ end
308
+
309
+ delegate :source, to: :params
310
+ end
311
+ ```
312
+
313
+ ### Operation::Flow
314
+
315
+ A streamlined interface for orchestrating and executing service operations with support for:
316
+
317
+ * typed parameters (via Dry::Types)
318
+ * typed responses (with translation helpers & inquiry methods)
319
+ * flow control (.on_success, .on_fail, .bind_with, .perform, etc.)
320
+
321
+ ```ruby
322
+ class SignupOperation < Toolx::Core::Operation
323
+ include Toolx::Core::Operation::Flow
324
+
325
+ params do
326
+ attribute :email, Types::String
327
+ attribute :age, Types::Integer
328
+ end
329
+
330
+ response do
331
+ include Toolx::Core::Concerns::Inquirer
332
+ attribute :status, Types::String
333
+ attribute :message, Types::String
334
+ inquirer :status
335
+ end
336
+
337
+ def perform
338
+ if age < 18
339
+ { status: 'error', message: 'You must be 18+' }
340
+ else
341
+ { status: 'success', message: "Welcome, #{email}" }
342
+ end
343
+ end
344
+ end
345
+ ```
346
+
347
+ 🚀 Execution Flow
348
+
349
+ Initialize, perform, and access result:
350
+
351
+ ```ruby
352
+ flow = SignupOperation.flow
353
+ executor = flow.perform(email: 'foo@bar.com', age: 20)
354
+
355
+ executor.response.status.success? # => true
356
+ executor.response.message # => "Welcome, foo@bar.com"
357
+ ```
358
+
359
+ Retry logic:
360
+
361
+ ```ruby
362
+ executor.perform! # Re-executes with same params
363
+ executor.perform!(email: ..., age: ...) # Replaces and re-executes
364
+ ```
365
+
366
+ 🔁 Handler Bindings
367
+
368
+ Symbolic method bindings:
369
+
370
+ ```ruby
371
+ SignupOperation.flow
372
+ .bind_with(self)
373
+ .on(success: :redirect_to_dashboard, fail: :render_form)
374
+ .perform(email: 'foo@bar.com', age: 17)
375
+ ```
376
+
377
+ Proc-style handler chaining:
378
+
379
+ ```ruby
380
+ SignupOperation.flow
381
+ .on_success { |resp, exec| notify_user(resp.message) }
382
+ .on_fail { |resp, exec| logger.warn("Failed: #{resp.message}") }
383
+ .perform!(email: 'foo@bar.com', age: 20)
384
+ ```
385
+
386
+ ### Stateman via with_state_machine
387
+
388
+ It is working only with `Statesman::Adapters::ActiveRecord`
389
+
390
+ You can generate state machine classes via rake task
391
+
392
+ ```bash
393
+ bin/rails "toolx:stateman:generate[Project]"
394
+ ```
395
+ command will generate models for existing `Project` model as
396
+ `Project::StateMachine` and `Project::Transition`.
397
+
398
+ also will add migraion file for those models.
399
+
400
+ Example usage:
401
+
402
+ ```ruby
403
+ class Project::StateMachine
404
+ include Statesman::Machine
405
+
406
+ state :active, initial: true
407
+ state :pending
408
+ state :skipped
409
+ state :cancelled
410
+ state :done
411
+
412
+ transition from: :active, to: [:pending, :pending, :skipped, :cancelled, :done]
413
+ transition from: :pending, to: [:skipped, :cancelled, :done]
414
+ transition from: :skipped, to: [:pending]
415
+
416
+ after_transition do |model, transition|
417
+ model.update!(status: transition.to_state)
418
+ end
419
+ end
420
+
421
+ class Project::Transition < ActiveRecord::Base
422
+ belongs_to :project
423
+
424
+ attribute :most_recent, :boolean, default: false
425
+ attribute :sort_key, :integer
426
+ attribute :to_state, :string
427
+ attribute :metadata, :json, default: {}
428
+
429
+ validates :to_state, inclusion: { in: Project::StateMachine.states }
430
+ end
431
+
432
+ class Project < ActiveRecord::Base
433
+ include Toolx::Core::Concerns::WithStateMachine
434
+ STATUSES = %w[active pending done skipped cancelled].freeze
435
+
436
+ with_state_machine
437
+
438
+ attribute :name, :string
439
+ attribute :status, :string, default: 'active'
440
+
441
+ validates :name, presence: true
442
+ validates :status, inclusion: { in: STATUSES }, allow_nil: true
443
+ end
444
+ ```
445
+
446
+ ## License
447
+
448
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
449
+
450
+ ## Code of Conduct
451
+
452
+ Everyone interacting in the Toolx project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/toolx/blob/master/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]
data/lib/tasks/.keep ADDED
File without changes