mu-action 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e178de7158d182e1527dd7b23ede20e67f9010e4bc588869fe433ebd4f2d1c85
4
+ data.tar.gz: 424feef48df8a60bd7c9aaf5ea755744d804f818e54fe2dd6d9a2ec4aea70595
5
+ SHA512:
6
+ metadata.gz: 7776bdf1fbb430638cb882abf2558d397b8dea4d7ea69c237ab9c3d9f0d3ddd5f05f4c66bb2cad79e16f02d2fb6b8a0b14d99bcba2bac01c99b5e8249763cc8d
7
+ data.tar.gz: aa9b022415a7905aa29ab543fed97763842e2b6ccf18e08e4b91b62479bf38651eb2dc518c9c5b7f49f3413f80de896886e534ac03473fabaaf6d82c1c250ccd
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,20 @@
1
+ AllCops:
2
+ NewCops: enable
3
+ TargetRubyVersion: 3.1
4
+ Exclude:
5
+ - readme_examples.rb
6
+
7
+ Metrics/BlockLength:
8
+ AllowedMethods:
9
+ - configure
10
+ - context
11
+ - define
12
+ - describe
13
+ - guard
14
+ - shared_examples
15
+
16
+ Style/StringLiterals:
17
+ EnforcedStyle: double_quotes
18
+
19
+ Style/StringLiteralsInInterpolation:
20
+ EnforcedStyle: double_quotes
data/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-07-23
4
+
5
+ ### Added
6
+ - Initial release of Mu::Action gem
7
+ - Interactor pattern implementation with type safety using Literal gem
8
+ - Support for Success/Failure result objects with metadata tracking
9
+ - Hook system with before, after, and around hooks
10
+ - Automatic property tracking in metadata
11
+ - Custom result types with type constraints
12
+ - Comprehensive documentation and examples
data/CLAUDE.md ADDED
@@ -0,0 +1,35 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Development Commands
6
+
7
+ - **Run tests**: `bundle exec rspec`
8
+ - **Run linting**: `bundle exec rubocop`
9
+ - **Run all checks**: `rake` (runs both spec and rubocop)
10
+ - **Interactive console**: `bin/console`
11
+ - **Install gem locally**: `bundle exec rake install`
12
+ - **Setup development environment**: `bin/setup`
13
+
14
+ ## Architecture Overview
15
+
16
+ This is a Ruby gem that provides an interactor pattern implementation
17
+ using the Literal gem for properties and type checking. The core module
18
+ `Mu::Action` is designed to be included in classes to provide:
19
+
20
+ ### Core Concepts
21
+
22
+ - Actions are classes that include `Mu::Action` and implement a `call` method
23
+ - Actions can be executed via `MyAction.call(...)` or `MyAction.call!(...)`
24
+ - Results are wrapped in `Result` objects with success/failure state and metadata
25
+ - Hooks allow for cross-cutting concerns and middleware-like behavior
26
+ - Properties are automatically tracked in metadata for debugging/logging
27
+
28
+ ### Dependencies
29
+
30
+ - **literal**: Core dependency for properties and type system
31
+ - **rspec**: Testing framework
32
+ - **rubocop**: Code linting and style enforcement
33
+
34
+ The gem follows standard Ruby gem conventions with lib/, spec/, and bin/
35
+ directories.
@@ -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,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ guard :rspec, cmd: "bundle exec rspec" do
4
+ require "guard/rspec/dsl"
5
+ dsl = Guard::RSpec::Dsl.new(self)
6
+
7
+ # Ruby files
8
+ ruby = dsl.ruby
9
+ dsl.watch_spec_files_for(ruby.lib_files)
10
+
11
+ # RSpec files
12
+ rspec = dsl.rspec
13
+ watch(rspec.spec_helper) { rspec.spec_dir }
14
+ watch(rspec.spec_support) { rspec.spec_dir }
15
+ watch(rspec.spec_files)
16
+
17
+ # Watch lib files
18
+ watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
19
+ watch(%r{^lib/mu/action/(.+)\.rb$}) { "spec/mu/action_spec.rb" }
20
+ watch(%r{^lib/mu/action\.rb$}) { Dir["spec/*"] }
21
+ end
22
+
23
+ guard :rubocop, cli: "--format progress" do
24
+ watch(/.+\.rb$/)
25
+ watch(%r{(?:.+/)?\.rubocop(?:_todo)?\.yml$}) { |m| File.dirname(m[0]) }
26
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Nicolas Buduroi
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,239 @@
1
+ # Mu::Action
2
+
3
+ `Mu::Action` is a Ruby gem that provides a modern interactor pattern implementation with enhanced type safety, metadata tracking, and a hook system. Built on top of the excellent [Literal](https://literal.fun) gem, it offers a structured approach to encapsulating business logic in single-purpose, composable objects.
4
+
5
+ This project is heavily inspired by the [Interactor](https://github.com/collectiveidea/interactor) gem.
6
+
7
+ ## What is an Interactor?
8
+
9
+ An interactor is a design pattern that encapsulates a single piece of business logic. Instead of cramming complex operations into controllers or models, interactors provide a clean, testable way to organize your application's core functionality.
10
+
11
+ Think of interactors as specialized service objects that:
12
+
13
+ - Have a single responsibility
14
+ - Receive input parameters
15
+ - Return structured results (success or failure)
16
+ - Can be easily tested in isolation
17
+ - Compose well with other interactors
18
+
19
+ Basically, it's like a component for your business logic.
20
+
21
+ ## Installation
22
+
23
+ Add this line to your application's Gemfile:
24
+
25
+ ```ruby
26
+ gem 'mu-action'
27
+ ```
28
+
29
+ And then execute:
30
+
31
+ ```bash
32
+ bundle install
33
+ ```
34
+
35
+ Or install it yourself as:
36
+
37
+ ```bash
38
+ gem install mu-action
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ ### Basic Interactor
44
+
45
+ Create an interactor by including `Mu::Action` and implementing a `call` method:
46
+
47
+ ```ruby
48
+ class CreateUser
49
+ include Mu::Action
50
+
51
+ prop :email, String
52
+ prop :name, String
53
+ prop :age, Integer, default: 18
54
+
55
+ def call
56
+ Failure(:user_exists) if User.exists?(email: @email)
57
+ user = User.create!(email: @email, name: @name, age: @age)
58
+ Success(user)
59
+ end
60
+ end
61
+ ```
62
+
63
+ ### Results
64
+
65
+ A `Success` result contains the `value` returned by the interactor, while a `Failure` result contains an `error` value. Both result types respond to `#success?` and `#failure?` methods to check their status. They also provide a `#meta` method to access metadata about the execution, such as the class name, properties.
66
+
67
+ A failure will return immediately.
68
+
69
+ ### Calling Interactors
70
+
71
+ Interactors can be called in two ways:
72
+
73
+ ```ruby
74
+ # Returns a Result object (Success or Failure)
75
+ result = CreateUser.call(email: "jane@example.com", name: "Jane")
76
+
77
+ case result
78
+ in Mu::Action::Success(value:)
79
+ puts "Created user: #{value.name}"
80
+ in Mu::Action::Failure(error:)
81
+ puts "Failed: #{error}"
82
+ end
83
+
84
+ # Returns the value on success, raises an exception on failure
85
+ user = CreateUser.call!(email: "jane@example.com", name: "Jane")
86
+ assert user.name == "Jane"
87
+ assert user.email == "jane@example.com"
88
+ ```
89
+
90
+ ### Hooks
91
+
92
+ Add cross-cutting concerns with before, after, and around hooks:
93
+
94
+ ```ruby
95
+ class ProcessPayment
96
+ include Mu::Action
97
+
98
+ prop :amount, Float
99
+ prop :card_token, String
100
+
101
+ before do
102
+ meta[:started_at] = Time.now
103
+ Rails.logger.info "Processing payment for $#{@amount}"
104
+ end
105
+
106
+ after do
107
+ meta[:completed_at] = Time.now
108
+ Rails.logger.info "Payment processing completed"
109
+ end
110
+
111
+ around do |action, chain|
112
+ ActiveRecord::Base.transaction do
113
+ chain.call
114
+ end
115
+ end
116
+
117
+ def call
118
+ # Payment processing logic here
119
+ Success(payment_id: "pay_123")
120
+ end
121
+ end
122
+
123
+ result = ProcessPayment.call(amount: 100.0, card_token: "tok_123")
124
+ assert result.value[:payment_id] == "pay_123"
125
+ ```
126
+
127
+ ### Custom Result Types
128
+
129
+ Define typed results for better API contracts:
130
+
131
+ ```ruby
132
+ class RollaDice
133
+ include Mu::Action
134
+
135
+ result _Integer(1..6)
136
+
137
+ def call
138
+ Success rand 1..6
139
+ end
140
+ end
141
+
142
+ result = RollaDice.call!
143
+ assert (1..6).cover? result
144
+ ```
145
+
146
+ The result method above is just a shortcut for the type of the value property of the Success class.
147
+
148
+ ```ruby
149
+ class RollaDice
150
+ include Mu::Action
151
+
152
+ class Success < Mu::Action::Success
153
+ prop :value, _Integer(1..6), :positional
154
+ end
155
+
156
+ def call
157
+ Success rand 1..6
158
+ end
159
+ end
160
+
161
+ result = RollaDice.call!
162
+ assert (1..6).cover? result
163
+ ```
164
+
165
+ You can refer to the [Literal documentation](https://literal.fun/docs) for more details on the [built-in types](https://literal.fun/docs/built-in-types.html) or see some [example types](https://literal.fun/docs/example-types.html).
166
+
167
+ ### Metadata Tracking
168
+
169
+ Every interactor automatically tracks metadata including class information and property values:
170
+
171
+ ```ruby
172
+ result = CreateUser.call(email: "test@example.com", name: "Test User")
173
+
174
+ assert result.meta == {
175
+ class: CreateUser,
176
+ props: { email: "test@example.com", name: "Test User", age: 18 }
177
+ }
178
+ ```
179
+
180
+ ## Differences from the Interactor Gem
181
+
182
+ The main difference and the motivation for creating `Mu::Action` is to separate the context into inputs, an output, and metadata. This allows for a more structured approach to handling business logic, making it easier to reason about the flow of data and the state of the application.
183
+
184
+ ## Development
185
+
186
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run the tests with:
187
+
188
+ ```bash
189
+ bundle exec rspec
190
+ ```
191
+
192
+ You can also run `bin/console` for an interactive prompt to experiment with the gem.
193
+
194
+ To install this gem onto your local machine, run `bundle exec rake install`.
195
+
196
+ ### Running Tests and Linting
197
+
198
+ ```bash
199
+ # Run all tests
200
+ bundle exec rspec
201
+
202
+ # Run linting
203
+ bundle exec rubocop
204
+
205
+ # Run both tests and linting
206
+ bundle exec rake
207
+ ```
208
+
209
+ ## Contributing
210
+
211
+ Bug reports and pull requests are welcome on GitHub at https://github.com/budu/mu-action.
212
+
213
+ When contributing:
214
+
215
+ 1. Fork the repository
216
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
217
+ 3. Write tests for your changes
218
+ 4. Ensure all tests pass (`bundle exec rspec`)
219
+ 5. Ensure code follows style guidelines (`bundle exec rubocop`)
220
+ 6. Commit your changes (`git commit -am 'Add some feature'`)
221
+ 7. Push to the branch (`git push origin my-new-feature`)
222
+ 8. Create a new Pull Request
223
+
224
+ 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/budu/mu-action/blob/main/CODE_OF_CONDUCT.md).
225
+
226
+ ## Acknowledgments
227
+
228
+ This project stands on the shoulders of giants:
229
+
230
+ - **[Interactor](https://github.com/collectiveidea/interactor)** by Steve Richert and contributors: The original inspiration for this gem.
231
+ - **[Literal](https://literal.fun)** by Joel Drapper and contributors: The type system that makes this gem possible.
232
+
233
+ ## License
234
+
235
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
236
+
237
+ ## Code of Conduct
238
+
239
+ Everyone interacting in the Mu::Action project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/budu/mu-action/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,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mu
4
+ module Action
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
data/lib/mu/action.rb ADDED
@@ -0,0 +1,190 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "action/version"
4
+ require "literal"
5
+
6
+ module Mu
7
+ # Provides an interactor pattern implementation with hooks, metadata tracking,
8
+ # and result wrapping.
9
+ module Action
10
+ def self.included(base)
11
+ base.class_eval do
12
+ extend Literal::Properties
13
+ extend ClassMethods
14
+ include Initializer
15
+ singleton_class.prepend(MetaPropAdder)
16
+ singleton_class.prepend(HookPropagator)
17
+
18
+ attr_reader :meta
19
+ end
20
+ end
21
+
22
+ # Internal module that automatically adds a meta property to action classes
23
+ # when they are instantiated. Ensures proper metadata initialization.
24
+ module MetaPropAdder
25
+ def new(...)
26
+ unless @meta_prop_added
27
+ prop :meta, Hash, default: -> { {} }
28
+ @meta_prop_added = true
29
+ end
30
+ instance = super
31
+ # Ensure meta is initialized for this specific class
32
+ instance.send(:initialize_meta) if instance.respond_to?(:initialize_meta, true)
33
+ instance
34
+ end
35
+
36
+ def inherited(subclass)
37
+ super
38
+ subclass.instance_variable_set(:@meta_prop_added, false)
39
+ end
40
+ end
41
+
42
+ # Internal module that ensures hook arrays are properly duplicated when
43
+ # action classes are inherited, preventing shared state between classes.
44
+ module HookPropagator
45
+ def inherited(subclass)
46
+ super
47
+ subclass.instance_variable_set(:@before_hooks, before_hooks.dup)
48
+ subclass.instance_variable_set(:@after_hooks, after_hooks.dup)
49
+ subclass.instance_variable_set(:@around_hooks, around_hooks.dup)
50
+ end
51
+ end
52
+
53
+ # Exception class for action failures. Wraps the original error
54
+ # and includes metadata for debugging and logging purposes.
55
+ class FailureError < StandardError
56
+ attr_reader :error, :meta
57
+
58
+ def initialize(error, meta: {})
59
+ @error = error
60
+ @meta = meta
61
+ super(error)
62
+ end
63
+ end
64
+
65
+ # Base result class that wraps action outcomes with success/failure state
66
+ # and metadata. Extended by Success and Failure classes for pattern matching.
67
+ class Result < Literal::Struct
68
+ prop :meta, Hash, default: -> { {} }
69
+
70
+ attr_reader :meta
71
+ end
72
+
73
+ # Success result class for pattern matching
74
+ class Success < Result
75
+ prop :value, _Any, :positional, default: nil
76
+
77
+ attr_reader :value
78
+
79
+ def success? = true
80
+ def failure? = false
81
+ end
82
+
83
+ # Failure result class for pattern matching
84
+ class Failure < Result
85
+ prop :error, _Any, :positional, default: nil
86
+
87
+ attr_reader :error
88
+
89
+ def success? = false
90
+ def failure? = true
91
+ end
92
+
93
+ # Internal module that handles action initialization, automatically
94
+ # tracking class information and property values in metadata.
95
+ module Initializer
96
+ def initialize(...)
97
+ super
98
+ initialize_meta
99
+ end
100
+
101
+ private
102
+
103
+ def initialize_meta
104
+ meta[:class] = self.class
105
+ meta[:props] = self.class.literal_properties.to_h do |prop|
106
+ [prop.name, instance_variable_get(:"@#{prop.name}")]
107
+ end.except(:meta)
108
+ end
109
+ end
110
+
111
+ # Class methods added to action classes when including Mu::Action.
112
+ # Provides hook registration, execution methods, and result type definition.
113
+ module ClassMethods
114
+ def around(&block) = around_hooks << block
115
+ def before(&block) = before_hooks << block
116
+ def after(&block) = after_hooks << block
117
+
118
+ def around_hooks = (@around_hooks ||= [])
119
+ def before_hooks = (@before_hooks ||= [])
120
+ def after_hooks = (@after_hooks ||= [])
121
+
122
+ def call(...) = new(...).run
123
+
124
+ def call!(...)
125
+ result = new(...).run!
126
+ case result
127
+ in Success(value:)
128
+ value
129
+ in Failure(meta: { failure_error: })
130
+ raise failure_error
131
+ else
132
+ result
133
+ end
134
+ end
135
+
136
+ def result(type)
137
+ success_class = Class.new(::Mu::Action::Success) do
138
+ prop :value, type, :positional, default: nil
139
+ end
140
+
141
+ const_set(:Success, success_class)
142
+ end
143
+ end
144
+
145
+ # rubocop:disable Naming/MethodName
146
+ def Success(value) = self.class.const_get(:Success).new(value, meta:)
147
+ def Failure(error, **meta) = raise FailureError.new(error, meta:)
148
+ # rubocop:enable Naming/MethodName
149
+
150
+ def run
151
+ run!
152
+ rescue FailureError => e
153
+ Failure.new(e.error, meta: { failure_error: e, **meta, **e.meta })
154
+ end
155
+
156
+ def run!
157
+ with_hooks { call }
158
+ end
159
+
160
+ protected
161
+
162
+ def result_class = self.class.const_get(:Result)
163
+
164
+ def with_hooks(&)
165
+ run_before_hooks
166
+ call_chain = build_around_chain(&)
167
+ result = call_chain.call
168
+ run_after_hooks
169
+ result
170
+ end
171
+
172
+ private
173
+
174
+ def run_before_hooks = self.class.before_hooks.each { instance_exec(&_1) }
175
+ def run_after_hooks = self.class.after_hooks.each { instance_exec(&_1) }
176
+
177
+ def build_around_chain(&block)
178
+ chain = block
179
+ self.class.around_hooks.reverse_each do |hook|
180
+ previous = chain
181
+ chain = -> { instance_exec(self, previous, &hook) }
182
+ end
183
+ chain
184
+ end
185
+
186
+ def call
187
+ raise NotImplementedError, "You must implement the call method"
188
+ end
189
+ end
190
+ end
data/sig/mu/action.rbs ADDED
@@ -0,0 +1,6 @@
1
+ module Mu
2
+ module Action
3
+ VERSION: String
4
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,75 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mu-action
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Nicolas Buduroi
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-07-24 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: literal
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.7'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.7'
27
+ description: A Ruby gem providing interactor pattern implementation with enhanced
28
+ type safety, metadata tracking, and hook system built on Literal gem
29
+ email:
30
+ - nbuduroi@gmail.com
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".rspec"
36
+ - ".rubocop.yml"
37
+ - CHANGELOG.md
38
+ - CLAUDE.md
39
+ - CODE_OF_CONDUCT.md
40
+ - Guardfile
41
+ - LICENSE.txt
42
+ - README.md
43
+ - Rakefile
44
+ - lib/mu/action.rb
45
+ - lib/mu/action/version.rb
46
+ - sig/mu/action.rbs
47
+ homepage: https://github.com/budu/mu-action
48
+ licenses:
49
+ - MIT
50
+ metadata:
51
+ allowed_push_host: https://rubygems.org
52
+ homepage_uri: https://github.com/budu/mu-action
53
+ source_code_uri: https://github.com/budu/mu-action
54
+ changelog_uri: https://github.com/budu/mu-action/blob/main/CHANGELOG.md
55
+ rubygems_mfa_required: 'true'
56
+ post_install_message:
57
+ rdoc_options: []
58
+ require_paths:
59
+ - lib
60
+ required_ruby_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: 3.1.0
65
+ required_rubygems_version: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: '0'
70
+ requirements: []
71
+ rubygems_version: 3.5.22
72
+ signing_key:
73
+ specification_version: 4
74
+ summary: Modern interactor pattern with type safety and metadata tracking
75
+ test_files: []