mu-action 0.1.0 → 0.3.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e178de7158d182e1527dd7b23ede20e67f9010e4bc588869fe433ebd4f2d1c85
4
- data.tar.gz: 424feef48df8a60bd7c9aaf5ea755744d804f818e54fe2dd6d9a2ec4aea70595
3
+ metadata.gz: 261d73076a857c43d7c68e5c3585cb3e96d693d54ed104b33abd6a6e897272fd
4
+ data.tar.gz: 9a0ac5c6592b3a2715918da63f88d8fec4b45dc6111547e1a545d6a26553e47e
5
5
  SHA512:
6
- metadata.gz: 7776bdf1fbb430638cb882abf2558d397b8dea4d7ea69c237ab9c3d9f0d3ddd5f05f4c66bb2cad79e16f02d2fb6b8a0b14d99bcba2bac01c99b5e8249763cc8d
7
- data.tar.gz: aa9b022415a7905aa29ab543fed97763842e2b6ccf18e08e4b91b62479bf38651eb2dc518c9c5b7f49f3413f80de896886e534ac03473fabaaf6d82c1c250ccd
6
+ metadata.gz: ef960929df4e5a7daa07544be3af52a5a952185959fbcc3a21329145e7e465c3f798ff46c0c382f4c63310fbfd3aa611e3e742f506fcbec949b80ebd1463adc4
7
+ data.tar.gz: 75a8de3adbc5dbaf4302f233c9314bedf009c5aebd4b12b32422a790a989e75073aaffc8303bc124e2c058b36ae88cd63b1bf37b7ed6edc84cda42fc5ab02b55
data/CHANGELOG.md CHANGED
@@ -1,5 +1,49 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.3.0] - 2026-11-14
4
+
5
+ ### Breaking
6
+ - Keyword arguments to `Failure` now go to the new `Failure#details` instead of being merged into `meta`. Read `result.details[:errors]` where you used `result.meta[:errors]`.
7
+ - `FailureError#meta` is replaced by `#details` and `#failure` (the `Failure` result, set when raised by `call!`).
8
+ - `call!` raises a new `FailureError` whose `cause` is the original one.
9
+
10
+ ### Added
11
+ - `failure` class method to declare an action's failures and the types of their details, plus `failures` to list them. `failure from: OtherAction` accepts the failures of another action.
12
+ - `Mu::Action.on_undeclared_failure`: `:raise` (default) or a callable receiving the action, error and details.
13
+ - A failure raised by a nested `call!` becomes the outer action's failure, with the inner `Failure` in `meta[:cause]`.
14
+ - `context:` keyword: caller information (actor, account, channel...) available as `context` in hooks and `call`, recorded in `meta[:context]`, and inherited by nested actions. `context` is now a reserved prop name.
15
+ - `record_props` class method: record every prop (default), none (`record_props false`), `only:` some or all `except:` some in `meta[:props]`.
16
+
17
+ ### Changed
18
+ - An action without a `result` type accepts `nil` as its success value, and `Success()` can be called without a value. Typed results still reject `nil` unless declared with `_Nilable`.
19
+ - Minimum Ruby version raised to 3.2 (3.1 is end-of-life).
20
+ - CI now tests Ruby 3.2, 3.3, 3.4 and 4.0.
21
+ - Development lockfile updated to Literal 1.9.0, RuboCop 1.92, Steep 2.0 and RBS 4.1. This fixes the Ruby 4.0 CI job (ffi) and the `tsort` warnings on Ruby 4.0.
22
+ - CI uses `actions/checkout@v7`, which runs on Node.js 24.
23
+
24
+ ### Removed
25
+ - The unused protected `result_class` method.
26
+ - Development files from the packaged gem, which now only contains `lib/mu/`, `sig/mu/` and the docs. `lib/guard/steep.rb` and the local RBS stubs for Kernel and Literal were shipped by mistake.
27
+
28
+ ### Fixed
29
+ - A `meta:` hash passed by a caller is no longer modified.
30
+ - `bin/test_readme_examples` now requires `fileutils`, which is no longer loaded indirectly on Ruby 3.4+.
31
+
32
+ ## [0.2.0] - 2025-10-30
33
+
34
+ ### Added
35
+ - Support registering `before`, `after`, and `around` hooks by method name.
36
+ - Steep type-checking infrastructure: Steepfile, comprehensive RBS signatures for `Mu::Action`.
37
+ - Guard plugin for steep type checking.
38
+
39
+ ### Changed
40
+ - `bin/check` now runs `bundle exec steep check` as part of the default contributor workflow.
41
+ - Guard automation reorganized to load the new Steep guard explicitly.
42
+ - Updated Bundler metadata to 2.7.2.
43
+
44
+ ### Documentation
45
+ - Added `AGENTS.md` with contributor and workflow guidelines.
46
+
3
47
  ## [0.1.0] - 2025-07-23
4
48
 
5
49
  ### Added
data/README.md CHANGED
@@ -62,7 +62,7 @@ end
62
62
 
63
63
  ### Results
64
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.
65
+ A `Success` result contains the `value` returned by the interactor, while a `Failure` result contains an `error` value, usually a symbol, and a `details` hash built from the keyword arguments given to `Failure`. 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 and properties. Metadata is for diagnostics; anything a caller needs belongs in `details`. An interactor with nothing to return can call `Success()` without a value.
66
66
 
67
67
  A failure will return immediately.
68
68
 
@@ -124,6 +124,41 @@ result = ProcessPayment.call(amount: 100.0, card_token: "tok_123")
124
124
  assert result.value[:payment_id] == "pay_123"
125
125
  ```
126
126
 
127
+ Hooks can also be registered by method name if you prefer keeping the logic in dedicated instance methods:
128
+
129
+ ```ruby
130
+ class ProcessPayment
131
+ include Mu::Action
132
+
133
+ prop :amount, Float
134
+ prop :card_token, String
135
+
136
+ before :prepare_logging
137
+ after :finalize_logging
138
+ around :wrap_in_transaction
139
+
140
+ def prepare_logging
141
+ meta[:started_at] = Time.now
142
+ Rails.logger.info "Processing payment for $#{@amount}"
143
+ end
144
+
145
+ def finalize_logging
146
+ meta[:completed_at] = Time.now
147
+ Rails.logger.info "Payment processing completed"
148
+ end
149
+
150
+ def wrap_in_transaction(chain)
151
+ ActiveRecord::Base.transaction { chain.call }
152
+ end
153
+
154
+ def call
155
+ Success(payment_id: "pay_123")
156
+ end
157
+ end
158
+ ```
159
+
160
+ Around hook methods may also receive no arguments and use `yield`, or accept two arguments `(action, chain)` to mirror the block-based signature.
161
+
127
162
  ### Custom Result Types
128
163
 
129
164
  Define typed results for better API contracts:
@@ -164,6 +199,81 @@ assert (1..6).cover? result
164
199
 
165
200
  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
201
 
202
+ ### Failures
203
+
204
+ `Failure` takes an error code and, optionally, details as keyword arguments:
205
+
206
+ ```ruby
207
+ class RenameProject
208
+ include Mu::Action
209
+
210
+ prop :name, String
211
+
212
+ def call
213
+ Failure(:invalid, errors: ["name can't be blank"]) if @name.empty?
214
+ Success(@name)
215
+ end
216
+ end
217
+
218
+ case RenameProject.call(name: "")
219
+ in Mu::Action::Failure(error: :invalid, details: { errors: })
220
+ assert errors == ["name can't be blank"]
221
+ end
222
+ ```
223
+
224
+ An interactor can declare the failures it returns, with the types of their details. Once it declares any, an undeclared failure or a detail of the wrong type raises an `ArgumentError`. Interactors without declarations accept any failure.
225
+
226
+ ```ruby
227
+ class PublishArticle
228
+ include Mu::Action
229
+
230
+ failure :already_published
231
+ failure :invalid, errors: _Array(String)
232
+
233
+ prop :title, String
234
+
235
+ def call
236
+ Failure(:invalid, errors: ["title is missing"]) if @title.empty?
237
+ Success(@title)
238
+ end
239
+ end
240
+
241
+ assert PublishArticle.failures.keys == %i[already_published invalid]
242
+ ```
243
+
244
+ To report undeclared failures instead of raising, give `Mu::Action.on_undeclared_failure` a callable. It receives the interactor, the error code and the details, and the failure goes through:
245
+
246
+ ```ruby
247
+ Mu::Action.on_undeclared_failure = lambda do |action, error, details|
248
+ Rails.logger.info "#{action.class} returned undeclared failure #{error.inspect}"
249
+ end
250
+
251
+ Mu::Action.on_undeclared_failure = :raise # the default
252
+ ```
253
+
254
+ To compose interactors, call the inner one with `call!`. Its failure becomes the outer interactor's failure, with the same error and details, and the inner `Failure` is kept in `meta[:cause]`. Use `failure from:` to accept every failure of the inner interactor:
255
+
256
+ ```ruby
257
+ class PublishFeaturedArticle
258
+ include Mu::Action
259
+
260
+ failure from: PublishArticle
261
+
262
+ prop :title, String
263
+
264
+ def call
265
+ title = PublishArticle.call!(title: @title)
266
+ Success("Featured: #{title}")
267
+ end
268
+ end
269
+
270
+ result = PublishFeaturedArticle.call(title: "")
271
+ assert result.error == :invalid
272
+ assert result.meta[:cause].meta[:class] == PublishArticle
273
+ ```
274
+
275
+ Because the inner failure is raised as an exception, around hooks such as transactions see it and can roll back.
276
+
167
277
  ### Metadata Tracking
168
278
 
169
279
  Every interactor automatically tracks metadata including class information and property values:
@@ -177,6 +287,46 @@ assert result.meta == {
177
287
  }
178
288
  ```
179
289
 
290
+ To keep sensitive or bulky props out of the metadata, choose which ones are recorded:
291
+
292
+ ```ruby
293
+ class SignIn
294
+ include Mu::Action
295
+
296
+ record_props except: %i[password] # or only: [...], or record_props false
297
+
298
+ prop :email, String
299
+ prop :password, String
300
+
301
+ def call = Success(@email)
302
+ end
303
+
304
+ assert SignIn.call(email: "jane@example.com", password: "secret").meta[:props] == { email: "jane@example.com" }
305
+ ```
306
+
307
+ ### Context
308
+
309
+ Information about who is calling and from where, such as the actor, the account or the channel, goes in `context` rather than in props. It's available in hooks and in `call`, and it's recorded in `meta[:context]`. It can be any object.
310
+
311
+ ```ruby
312
+ class ArchiveProject
313
+ include Mu::Action
314
+
315
+ prop :project_id, Integer
316
+
317
+ before do
318
+ meta[:archived_by] = context[:actor]
319
+ end
320
+
321
+ def call = Success(@project_id)
322
+ end
323
+
324
+ result = ArchiveProject.call(project_id: 42, context: { actor: "jane", channel: :web })
325
+ assert result.meta[:archived_by] == "jane"
326
+ ```
327
+
328
+ Interactors called by another one inherit its context, so a hook in a nested interactor sees the same actor. Pass `context:` explicitly to override it.
329
+
180
330
  ## Differences from the Interactor Gem
181
331
 
182
332
  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.
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Mu
4
4
  module Action
5
- VERSION = "0.1.0"
5
+ VERSION = "0.3.0"
6
6
  end
7
7
  end
data/lib/mu/action.rb CHANGED
@@ -7,24 +7,51 @@ module Mu
7
7
  # Provides an interactor pattern implementation with hooks, metadata tracking,
8
8
  # and result wrapping.
9
9
  module Action
10
+ # Global settings, available as Mu::Action.on_undeclared_failure and so on.
11
+ module Configuration
12
+ # How an action handles a failure that its declarations don't allow:
13
+ # +:raise+ (the default) raises an ArgumentError, while a callable is
14
+ # called with the action, the error code and the details.
15
+ attr_reader :on_undeclared_failure
16
+
17
+ def on_undeclared_failure=(handler)
18
+ unless handler == :raise || handler.respond_to?(:call)
19
+ raise ArgumentError, "on_undeclared_failure must be :raise or respond to #call"
20
+ end
21
+
22
+ @on_undeclared_failure = handler
23
+ end
24
+ end
25
+
26
+ extend Configuration
27
+
28
+ self.on_undeclared_failure = :raise
29
+
30
+ # Fiber storage key holding the context of the running action, inherited
31
+ # by the actions it calls.
32
+ CONTEXT_KEY = :mu_action_context
33
+
10
34
  def self.included(base)
11
35
  base.class_eval do
12
36
  extend Literal::Properties
13
37
  extend ClassMethods
14
38
  include Initializer
39
+ include FailureChecking
15
40
  singleton_class.prepend(MetaPropAdder)
16
41
  singleton_class.prepend(HookPropagator)
17
42
 
18
- attr_reader :meta
43
+ attr_reader :meta, :context
19
44
  end
20
45
  end
21
46
 
22
- # Internal module that automatically adds a meta property to action classes
23
- # when they are instantiated. Ensures proper metadata initialization.
47
+ # Internal module that automatically adds the meta and context properties
48
+ # to action classes when they are instantiated. Ensures proper metadata
49
+ # initialization.
24
50
  module MetaPropAdder
25
51
  def new(...)
26
52
  unless @meta_prop_added
27
- prop :meta, Hash, default: -> { {} }
53
+ prop :meta, Hash, default: -> { {} } # steep:ignore UnannotatedEmptyCollection
54
+ prop :context, _Nilable(_Any), default: -> { Fiber[CONTEXT_KEY] }
28
55
  @meta_prop_added = true
29
56
  end
30
57
  instance = super
@@ -39,25 +66,30 @@ module Mu
39
66
  end
40
67
  end
41
68
 
42
- # Internal module that ensures hook arrays are properly duplicated when
43
- # action classes are inherited, preventing shared state between classes.
69
+ # Internal module that ensures hook arrays and failure declarations are
70
+ # properly duplicated when action classes are inherited, preventing shared
71
+ # state between classes.
44
72
  module HookPropagator
45
73
  def inherited(subclass)
46
74
  super
47
75
  subclass.instance_variable_set(:@before_hooks, before_hooks.dup)
48
76
  subclass.instance_variable_set(:@after_hooks, after_hooks.dup)
49
77
  subclass.instance_variable_set(:@around_hooks, around_hooks.dup)
78
+ subclass.instance_variable_set(:@own_failures, own_failures.dup)
79
+ subclass.instance_variable_set(:@failure_sources, failure_sources.dup)
80
+ subclass.instance_variable_set(:@props_recording, props_recording)
50
81
  end
51
82
  end
52
83
 
53
- # Exception class for action failures. Wraps the original error
54
- # and includes metadata for debugging and logging purposes.
84
+ # Exception class for action failures. Carries the error code and its
85
+ # details. When raised by +call!+, it also carries the Failure result.
55
86
  class FailureError < StandardError
56
- attr_reader :error, :meta
87
+ attr_reader :error, :details, :failure
57
88
 
58
- def initialize(error, meta: {})
89
+ def initialize(error, details: {}, failure: nil)
59
90
  @error = error
60
- @meta = meta
91
+ @details = details
92
+ @failure = failure
61
93
  super(error)
62
94
  end
63
95
  end
@@ -65,14 +97,14 @@ module Mu
65
97
  # Base result class that wraps action outcomes with success/failure state
66
98
  # and metadata. Extended by Success and Failure classes for pattern matching.
67
99
  class Result < Literal::Struct
68
- prop :meta, Hash, default: -> { {} }
100
+ prop :meta, Hash, default: -> { {} } # steep:ignore UnannotatedEmptyCollection
69
101
 
70
102
  attr_reader :meta
71
103
  end
72
104
 
73
105
  # Success result class for pattern matching
74
106
  class Success < Result
75
- prop :value, _Any, :positional, default: nil
107
+ prop :value, _Nilable(_Any), :positional
76
108
 
77
109
  attr_reader :value
78
110
 
@@ -82,9 +114,10 @@ module Mu
82
114
 
83
115
  # Failure result class for pattern matching
84
116
  class Failure < Result
85
- prop :error, _Any, :positional, default: nil
117
+ prop :error, _Any, :positional
118
+ prop :details, Hash, default: -> { {} } # steep:ignore UnannotatedEmptyCollection
86
119
 
87
- attr_reader :error
120
+ attr_reader :error, :details
88
121
 
89
122
  def success? = false
90
123
  def failure? = true
@@ -101,19 +134,84 @@ module Mu
101
134
  private
102
135
 
103
136
  def initialize_meta
137
+ @meta = meta.dup
104
138
  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)
139
+ props = recorded_props
140
+ meta[:props] = props if props
141
+ meta[:context] = context unless context.nil?
142
+ end
143
+
144
+ def recorded_props
145
+ recording = self.class.props_recording
146
+ return if recording == false
147
+
148
+ props = self.class.literal_properties.to_h do |prop|
149
+ [prop.name, instance_variable_get(:"@#{prop.name}")] #: [Symbol, untyped]
150
+ end.except(:meta, :context)
151
+
152
+ case recording
153
+ in { only: } then props.slice(*only)
154
+ in { except: } then props.except(*except)
155
+ else props
156
+ end
157
+ end
158
+ end
159
+
160
+ # Internal module that builds Failure results and checks failures against
161
+ # the action's declarations.
162
+ module FailureChecking
163
+ private
164
+
165
+ def failure_from(exception)
166
+ cause = exception.failure
167
+ check_failure(exception.error, exception.details, origin: cause.meta[:class]) if cause
168
+ # @type var failure_meta: ::Hash[Symbol, untyped]
169
+ failure_meta = { **meta, failure_error: exception }
170
+ failure_meta[:cause] = cause if cause
171
+ Failure.new(exception.error, details: exception.details, meta: failure_meta)
172
+ end
173
+
174
+ def check_failure(error, details, origin: nil)
175
+ return unless self.class.declares_failures?
176
+ return if origin && self.class.failure_sources.any? { origin <= _1 }
177
+
178
+ problem = failure_problem(error, details)
179
+ return unless problem
180
+
181
+ case (handler = Mu::Action.on_undeclared_failure)
182
+ when :raise then raise ArgumentError, "#{self.class}: #{problem}"
183
+ else handler.call(self, error, details)
184
+ end
185
+ end
186
+
187
+ def failure_problem(error, details)
188
+ failures = self.class.failures
189
+ return "undeclared failure #{error.inspect}" unless failures.key?(error)
190
+
191
+ types = failures[error]
192
+ unexpected = details.keys - types.keys
193
+ return "unexpected details #{unexpected.inspect} for failure #{error.inspect}" if unexpected.any?
194
+
195
+ detail_problem(error, types, details)
196
+ end
197
+
198
+ def detail_problem(error, types, details)
199
+ types.each do |key, type|
200
+ value = details[key]
201
+ next if type === value # rubocop:disable Style/CaseEquality
202
+
203
+ return "detail #{key.inspect} of failure #{error.inspect} must be #{type.inspect}, got #{value.inspect}"
204
+ end
205
+ nil
108
206
  end
109
207
  end
110
208
 
111
209
  # Class methods added to action classes when including Mu::Action.
112
210
  # Provides hook registration, execution methods, and result type definition.
113
211
  module ClassMethods
114
- def around(&block) = around_hooks << block
115
- def before(&block) = before_hooks << block
116
- def after(&block) = after_hooks << block
212
+ def around(*method_names, &block) = register_hook(around_hooks, method_names, block, name: :around)
213
+ def before(*method_names, &block) = register_hook(before_hooks, method_names, block, name: :before)
214
+ def after(*method_names, &block) = register_hook(after_hooks, method_names, block, name: :after)
117
215
 
118
216
  def around_hooks = (@around_hooks ||= [])
119
217
  def before_hooks = (@before_hooks ||= [])
@@ -122,44 +220,136 @@ module Mu
122
220
  def call(...) = new(...).run
123
221
 
124
222
  def call!(...)
125
- result = new(...).run!
223
+ result = new(...).run
126
224
  case result
127
225
  in Success(value:)
128
226
  value
129
- in Failure(meta: { failure_error: })
130
- raise failure_error
227
+ in Failure(error:, details:, meta:)
228
+ raise FailureError.new(error, details:, failure: result), cause: meta[:failure_error]
131
229
  else
132
230
  result
133
231
  end
134
232
  end
135
233
 
234
+ # Chooses which props are recorded in meta[:props]: all of them (the
235
+ # default), none, or a subset.
236
+ #
237
+ # record_props false
238
+ # record_props only: %i[site_id]
239
+ # record_props except: %i[payload]
240
+ def record_props(enabled = true, only: nil, except: nil) # rubocop:disable Style/OptionalBooleanParameter
241
+ @props_recording = build_props_recording(enabled, only, except)
242
+ end
243
+
244
+ def props_recording = (defined?(@props_recording) ? @props_recording : true)
245
+
246
+ # Declares the failures this action can return. Once an action declares
247
+ # any, other failures are handled by Mu::Action.on_undeclared_failure.
248
+ #
249
+ # failure :site_disabled
250
+ # failure :invalid, errors: ActiveModel::Errors
251
+ # failure from: OtherAction
252
+ def failure(*codes, from: nil, **details)
253
+ raise ArgumentError, "failure requires a code or from:" if codes.empty? && !from
254
+ raise ArgumentError, "details can only be declared for a single failure" if codes.size > 1 && details.any?
255
+
256
+ codes.each { own_failures[_1] = details }
257
+ failure_sources.concat(Array(from))
258
+ end
259
+
260
+ # The declared failures, including those of the +from:+ actions,
261
+ # as a hash of error code to details types.
262
+ def failures
263
+ failure_sources.map(&:failures).reduce({}, :merge).merge(own_failures)
264
+ end
265
+
266
+ def declares_failures? = own_failures.any? || failure_sources.any?
267
+ def own_failures = (@own_failures ||= {})
268
+ def failure_sources = (@failure_sources ||= [])
269
+
136
270
  def result(type)
137
271
  success_class = Class.new(::Mu::Action::Success) do
138
- prop :value, type, :positional, default: nil
272
+ # @type self: singleton(::Mu::Action::Success)
273
+ prop :value, type, :positional
139
274
  end
140
275
 
141
276
  const_set(:Success, success_class)
142
277
  end
278
+
279
+ private
280
+
281
+ def build_props_recording(enabled, only, except)
282
+ raise ArgumentError, "record_props accepts only: or except:, not both" if only && except
283
+
284
+ # @type var filter: ::Hash[Symbol, ::Array[Symbol]]
285
+ filter = { only:, except: }.compact.transform_values { Array(_1) }
286
+ return filter.empty? || filter if enabled
287
+ raise ArgumentError, "record_props false accepts no only: or except:" if filter.any?
288
+
289
+ false
290
+ end
291
+
292
+ def register_hook(collection, method_names, block, name:)
293
+ ensure_valid_hook_inputs(method_names, block, name:)
294
+ additions = normalize_hook_inputs(method_names, block, name:)
295
+ collection.concat(additions)
296
+ end
297
+
298
+ def normalize_hook_inputs(method_names, block, name:)
299
+ if block
300
+ [block]
301
+ else
302
+ symbolize_hook_names(method_names, name:)
303
+ end
304
+ end
305
+
306
+ def ensure_valid_hook_inputs(method_names, block, name:)
307
+ return unless block && method_names.any?
308
+
309
+ raise ArgumentError, "#{name} hooks accept either a block or method names, not both"
310
+ end
311
+
312
+ def symbolize_hook_names(method_names, name:)
313
+ raise ArgumentError, "#{name} hook requires a block or method name" if method_names.empty?
314
+
315
+ method_names.map do |method_name|
316
+ unless method_name.respond_to?(:to_sym)
317
+ raise ArgumentError, "Invalid #{name} hook identifier: #{method_name.inspect}"
318
+ end
319
+
320
+ method_name.to_sym
321
+ end
322
+ end
143
323
  end
144
324
 
145
325
  # 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:)
326
+ def Success(value = nil) = self.class.const_get(:Success).new(value, meta:)
327
+
328
+ def Failure(error, **details)
329
+ check_failure(error, details)
330
+ raise FailureError.new(error, details:)
331
+ end
148
332
  # rubocop:enable Naming/MethodName
149
333
 
150
334
  def run
151
335
  run!
152
336
  rescue FailureError => e
153
- Failure.new(e.error, meta: { failure_error: e, **meta, **e.meta })
337
+ failure_from(e)
154
338
  end
155
339
 
156
340
  def run!
157
- with_hooks { call }
341
+ with_context { with_hooks { call } }
158
342
  end
159
343
 
160
344
  protected
161
345
 
162
- def result_class = self.class.const_get(:Result)
346
+ def with_context
347
+ previous = Fiber[CONTEXT_KEY]
348
+ Fiber[CONTEXT_KEY] = context
349
+ yield
350
+ ensure
351
+ Fiber[CONTEXT_KEY] = previous
352
+ end
163
353
 
164
354
  def with_hooks(&)
165
355
  run_before_hooks
@@ -171,18 +361,60 @@ module Mu
171
361
 
172
362
  private
173
363
 
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) }
364
+ def run_before_hooks = self.class.before_hooks.each { execute_simple_hook(_1) }
365
+ def run_after_hooks = self.class.after_hooks.each { execute_simple_hook(_1) }
176
366
 
177
367
  def build_around_chain(&block)
178
368
  chain = block
179
369
  self.class.around_hooks.reverse_each do |hook|
180
370
  previous = chain
181
- chain = -> { instance_exec(self, previous, &hook) }
371
+ chain = build_around_wrapper(hook, previous)
182
372
  end
183
373
  chain
184
374
  end
185
375
 
376
+ def execute_simple_hook(hook)
377
+ if hook.is_a?(Proc)
378
+ # @type var hook: ^(*untyped) -> untyped
379
+ return instance_exec(&hook)
380
+ end
381
+
382
+ send(hook)
383
+ end
384
+
385
+ def build_around_wrapper(hook, previous)
386
+ case hook
387
+ when Proc
388
+ lambda do
389
+ # @type var hook: ^(*untyped) -> untyped
390
+ instance_exec(self, previous, &hook)
391
+ end
392
+ else
393
+ -> { invoke_around_method(hook, previous) }
394
+ end
395
+ end
396
+
397
+ def invoke_around_method(hook, previous)
398
+ method_name = hook.to_sym
399
+ method_object = resolve_method(method_name)
400
+ arguments = around_arguments(method_object, previous)
401
+ method_object.bind(self).call(*arguments, &previous)
402
+ end
403
+
404
+ def around_arguments(method_object, previous)
405
+ params = method_object.parameters.reject { _1.first == :block }
406
+ return [] if params.empty?
407
+ return [previous] if params.length == 1
408
+
409
+ [self, previous]
410
+ end
411
+
412
+ def resolve_method(method_name)
413
+ self.class.instance_method(method_name)
414
+ rescue NameError
415
+ raise NoMethodError, "Undefined hook method ##{method_name} for #{self.class}"
416
+ end
417
+
186
418
  def call
187
419
  raise NotImplementedError, "You must implement the call method"
188
420
  end
data/sig/mu/action.rbs CHANGED
@@ -1,6 +1,159 @@
1
1
  module Mu
2
2
  module Action
3
- VERSION: String
4
- # See the writing guide of rbs: https://github.com/ruby/rbs#guides
3
+ include Kernel
4
+
5
+ VERSION: ::String
6
+
7
+ CONTEXT_KEY: Symbol
8
+
9
+ type failure_handler = :raise | ^(untyped action, untyped error, ::Hash[Symbol, untyped] details) -> untyped
10
+ type props_recording = bool | ::Hash[Symbol, ::Array[Symbol]]
11
+
12
+ module Configuration : Kernel
13
+ @on_undeclared_failure: failure_handler
14
+
15
+ def on_undeclared_failure: () -> failure_handler
16
+ def on_undeclared_failure=: (failure_handler handler) -> failure_handler
17
+ end
18
+
19
+ extend Configuration
20
+ attr_reader meta: ::Hash[untyped, untyped]
21
+ attr_reader context: untyped
22
+
23
+ interface _ActionInstance
24
+ def meta: () -> ::Hash[untyped, untyped]
25
+ def context: () -> untyped
26
+ def class: () -> _ActionClass
27
+ def run: () -> ::Mu::Action::Result
28
+ def run!: () -> ::Mu::Action::Result
29
+ end
30
+
31
+ interface _ActionClass
32
+ def literal_properties: () -> ::Array[untyped]
33
+ def before_hooks: () -> ::Array[untyped]
34
+ def after_hooks: () -> ::Array[untyped]
35
+ def around_hooks: () -> ::Array[untyped]
36
+ def declares_failures?: () -> bool
37
+ def failures: () -> ::Hash[untyped, ::Hash[Symbol, untyped]]
38
+ def failure_sources: () -> ::Array[_ActionClass]
39
+ def props_recording: () -> props_recording
40
+ def const_get: (Symbol) -> ::Class
41
+ def instance_method: (Symbol) -> UnboundMethod
42
+ def new: (*untyped, **untyped) -> _ActionInstance
43
+ end
44
+
45
+ def self.included: (untyped base) -> void
46
+ def self.before_hooks: () -> ::Array[untyped]
47
+ def self.after_hooks: () -> ::Array[untyped]
48
+ def self.around_hooks: () -> ::Array[untyped]
49
+
50
+ module MetaPropAdder
51
+ include Literal::Properties
52
+
53
+ def new: (*untyped, **untyped) -> untyped
54
+ def inherited: (untyped subclass) -> void
55
+ end
56
+
57
+ module HookPropagator
58
+ def inherited: (untyped subclass) -> void
59
+ def before_hooks: () -> ::Array[untyped]
60
+ def after_hooks: () -> ::Array[untyped]
61
+ def around_hooks: () -> ::Array[untyped]
62
+ def own_failures: () -> ::Hash[untyped, ::Hash[Symbol, untyped]]
63
+ def failure_sources: () -> ::Array[_ActionClass]
64
+ def props_recording: () -> props_recording
65
+ end
66
+
67
+ class FailureError < StandardError
68
+ attr_reader error: untyped
69
+ attr_reader details: ::Hash[Symbol, untyped]
70
+ attr_reader failure: Failure?
71
+
72
+ def initialize: (untyped error, ?details: ::Hash[Symbol, untyped], ?failure: Failure?) -> void
73
+ end
74
+
75
+ class Result < Literal::Struct
76
+ attr_reader meta: ::Hash[untyped, untyped]
77
+
78
+ def initialize: (*untyped, **untyped) -> void
79
+ end
80
+
81
+ class Success < Result
82
+ attr_reader value: untyped
83
+
84
+ def initialize: (*untyped, **untyped) -> void
85
+ def success?: () -> true
86
+ def failure?: () -> false
87
+ end
88
+
89
+ class Failure < Result
90
+ attr_reader error: untyped
91
+ attr_reader details: ::Hash[Symbol, untyped]
92
+
93
+ def initialize: (*untyped, **untyped) -> void
94
+ def success?: () -> false
95
+ def failure?: () -> true
96
+ end
97
+
98
+ module Initializer : _ActionInstance
99
+ @meta: ::Hash[untyped, untyped]
100
+
101
+ def initialize: (*untyped, **untyped) -> void
102
+ def initialize_meta: () -> void
103
+ def recorded_props: () -> ::Hash[Symbol, untyped]?
104
+ end
105
+
106
+ module FailureChecking : _ActionInstance
107
+ def failure_from: (FailureError exception) -> Failure
108
+ def check_failure: (untyped error, ::Hash[Symbol, untyped] details, ?origin: untyped) -> void
109
+ def failure_problem: (untyped error, ::Hash[Symbol, untyped] details) -> ::String?
110
+ def detail_problem: (untyped error, ::Hash[Symbol, untyped] types, ::Hash[Symbol, untyped] details) -> ::String?
111
+ end
112
+
113
+ module ClassMethods
114
+ include Literal::Properties
115
+
116
+ def around: (*Symbol) ?{ (*untyped) -> untyped } -> ::Array[untyped]
117
+ def before: (*Symbol) ?{ (*untyped) -> untyped } -> ::Array[untyped]
118
+ def after: (*Symbol) ?{ (*untyped) -> untyped } -> ::Array[untyped]
119
+ def around_hooks: () -> ::Array[untyped]
120
+ def before_hooks: () -> ::Array[untyped]
121
+ def after_hooks: () -> ::Array[untyped]
122
+ def call: (*untyped, **untyped) -> untyped
123
+ def call!: (*untyped, **untyped) -> untyped
124
+ def result: (untyped type) -> ::Class
125
+ def failure: (*untyped codes, ?from: untyped, **untyped details) -> ::Array[_ActionClass]
126
+ def failures: () -> ::Hash[untyped, ::Hash[Symbol, untyped]]
127
+ def declares_failures?: () -> bool
128
+ def own_failures: () -> ::Hash[untyped, ::Hash[Symbol, untyped]]
129
+ def failure_sources: () -> ::Array[_ActionClass]
130
+ def record_props: (?bool enabled, ?only: (Symbol | ::Array[Symbol])?, ?except: (Symbol | ::Array[Symbol])?) -> props_recording
131
+ def props_recording: () -> props_recording
132
+ def build_props_recording: (bool enabled, (Symbol | ::Array[Symbol])? only, (Symbol | ::Array[Symbol])? except) -> props_recording
133
+ def register_hook: (untyped collection, untyped method_names, ::Proc? block, name: Symbol) -> untyped
134
+ def normalize_hook_inputs: (untyped method_names, ::Proc? block, name: Symbol) -> untyped
135
+ def ensure_valid_hook_inputs: (untyped method_names, ::Proc? block, name: Symbol) -> void
136
+ def symbolize_hook_names: (untyped method_names, name: Symbol) -> ::Array[Symbol]
137
+ def const_set: (Symbol, ::Class) -> ::Class
138
+ def new: (*untyped, **untyped) -> _ActionInstance
139
+ end
140
+
141
+ def Success: (?untyped value) -> Success
142
+ def Failure: (untyped error, **untyped) -> bot
143
+ def run: () -> Result
144
+ def run!: () -> Result
145
+ def with_context: [T] () { () -> T } -> T
146
+ def failure_from: (FailureError exception) -> Failure
147
+ def check_failure: (untyped error, ::Hash[Symbol, untyped] details, ?origin: untyped) -> void
148
+ def with_hooks: () { () -> Result } -> Result
149
+ def run_before_hooks: () -> ::Array[untyped]
150
+ def run_after_hooks: () -> ::Array[untyped]
151
+ def build_around_chain: () { () -> Result } -> ::Proc
152
+ def execute_simple_hook: (::Proc | ::Symbol) -> untyped
153
+ def build_around_wrapper: ((::Proc | ::Symbol), ::Proc) -> ::Proc
154
+ def invoke_around_method: (::Symbol, ::Proc) -> untyped
155
+ def around_arguments: (UnboundMethod, ::Proc) -> ::Array[untyped]
156
+ def resolve_method: (Symbol) -> UnboundMethod
157
+ def call: () -> untyped
5
158
  end
6
159
  end
metadata CHANGED
@@ -1,14 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: mu-action
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nicolas Buduroi
8
- autorequire:
9
8
  bindir: exe
10
9
  cert_chain: []
11
- date: 2025-07-24 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
13
  name: literal
@@ -32,15 +31,9 @@ executables: []
32
31
  extensions: []
33
32
  extra_rdoc_files: []
34
33
  files:
35
- - ".rspec"
36
- - ".rubocop.yml"
37
34
  - CHANGELOG.md
38
- - CLAUDE.md
39
- - CODE_OF_CONDUCT.md
40
- - Guardfile
41
35
  - LICENSE.txt
42
36
  - README.md
43
- - Rakefile
44
37
  - lib/mu/action.rb
45
38
  - lib/mu/action/version.rb
46
39
  - sig/mu/action.rbs
@@ -49,11 +42,9 @@ licenses:
49
42
  - MIT
50
43
  metadata:
51
44
  allowed_push_host: https://rubygems.org
52
- homepage_uri: https://github.com/budu/mu-action
53
45
  source_code_uri: https://github.com/budu/mu-action
54
46
  changelog_uri: https://github.com/budu/mu-action/blob/main/CHANGELOG.md
55
47
  rubygems_mfa_required: 'true'
56
- post_install_message:
57
48
  rdoc_options: []
58
49
  require_paths:
59
50
  - lib
@@ -61,15 +52,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
61
52
  requirements:
62
53
  - - ">="
63
54
  - !ruby/object:Gem::Version
64
- version: 3.1.0
55
+ version: 3.2.0
65
56
  required_rubygems_version: !ruby/object:Gem::Requirement
66
57
  requirements:
67
58
  - - ">="
68
59
  - !ruby/object:Gem::Version
69
60
  version: '0'
70
61
  requirements: []
71
- rubygems_version: 3.5.22
72
- signing_key:
62
+ rubygems_version: 4.0.3
73
63
  specification_version: 4
74
64
  summary: Modern interactor pattern with type safety and metadata tracking
75
65
  test_files: []
data/.rspec DELETED
@@ -1,2 +0,0 @@
1
- --color
2
- --require spec_helper
data/.rubocop.yml DELETED
@@ -1,20 +0,0 @@
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/CLAUDE.md DELETED
@@ -1,35 +0,0 @@
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.
data/CODE_OF_CONDUCT.md DELETED
@@ -1,132 +0,0 @@
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 DELETED
@@ -1,26 +0,0 @@
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/Rakefile DELETED
@@ -1,12 +0,0 @@
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]