mu-action 0.2.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: 5765a5a8a0a0af6628f4b36d5e7dde4337eb44ed1e44275208b151276d4de412
4
- data.tar.gz: 6c906cf41b59a6fde0b7b4482d3029fca4a48f2767a4958f0d9d54a9ed661d79
3
+ metadata.gz: 261d73076a857c43d7c68e5c3585cb3e96d693d54ed104b33abd6a6e897272fd
4
+ data.tar.gz: 9a0ac5c6592b3a2715918da63f88d8fec4b45dc6111547e1a545d6a26553e47e
5
5
  SHA512:
6
- metadata.gz: 9c6f9145debfaee371e5330f8922d8739489358e5aaf7aa6d6d4f5ab1c445a880725a9314d3bf1d7ceddc1b9209a41ac68638dc9aba40985280d295f08250468
7
- data.tar.gz: 6a5b5a71d34add535fcb0672963a99c8414e8038776d376cc04bb81c8bc9d7fbe68561a7c2f7ef5ab10740ddaf02b6348bd85e9c8f8fedd7afd32e4e2126bd14
6
+ metadata.gz: ef960929df4e5a7daa07544be3af52a5a952185959fbcc3a21329145e7e465c3f798ff46c0c382f4c63310fbfd3aa611e3e742f506fcbec949b80ebd1463adc4
7
+ data.tar.gz: 75a8de3adbc5dbaf4302f233c9314bedf009c5aebd4b12b32422a790a989e75073aaffc8303bc124e2c058b36ae88cd63b1bf37b7ed6edc84cda42fc5ab02b55
data/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
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
+
3
32
  ## [0.2.0] - 2025-10-30
4
33
 
5
34
  ### 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
 
@@ -199,6 +199,81 @@ assert (1..6).cover? result
199
199
 
200
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).
201
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
+
202
277
  ### Metadata Tracking
203
278
 
204
279
  Every interactor automatically tracks metadata including class information and property values:
@@ -212,6 +287,46 @@ assert result.meta == {
212
287
  }
213
288
  ```
214
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
+
215
330
  ## Differences from the Interactor Gem
216
331
 
217
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.2.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
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
@@ -72,7 +104,7 @@ module Mu
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,10 +134,75 @@ 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
 
@@ -122,20 +220,57 @@ 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)
@@ -143,6 +278,17 @@ module Mu
143
278
 
144
279
  private
145
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
+
146
292
  def register_hook(collection, method_names, block, name:)
147
293
  ensure_valid_hook_inputs(method_names, block, name:)
148
294
  additions = normalize_hook_inputs(method_names, block, name:)
@@ -177,23 +323,33 @@ module Mu
177
323
  end
178
324
 
179
325
  # rubocop:disable Naming/MethodName
180
- def Success(value) = self.class.const_get(:Success).new(value, meta:)
181
- 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
182
332
  # rubocop:enable Naming/MethodName
183
333
 
184
334
  def run
185
335
  run!
186
336
  rescue FailureError => e
187
- Failure.new(e.error, meta: { failure_error: e, **meta, **e.meta })
337
+ failure_from(e)
188
338
  end
189
339
 
190
340
  def run!
191
- with_hooks { call }
341
+ with_context { with_hooks { call } }
192
342
  end
193
343
 
194
344
  protected
195
345
 
196
- 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
197
353
 
198
354
  def with_hooks(&)
199
355
  run_before_hooks
data/sig/mu/action.rbs CHANGED
@@ -3,10 +3,26 @@ module Mu
3
3
  include Kernel
4
4
 
5
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
6
20
  attr_reader meta: ::Hash[untyped, untyped]
21
+ attr_reader context: untyped
7
22
 
8
23
  interface _ActionInstance
9
24
  def meta: () -> ::Hash[untyped, untyped]
25
+ def context: () -> untyped
10
26
  def class: () -> _ActionClass
11
27
  def run: () -> ::Mu::Action::Result
12
28
  def run!: () -> ::Mu::Action::Result
@@ -17,6 +33,10 @@ module Mu
17
33
  def before_hooks: () -> ::Array[untyped]
18
34
  def after_hooks: () -> ::Array[untyped]
19
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
20
40
  def const_get: (Symbol) -> ::Class
21
41
  def instance_method: (Symbol) -> UnboundMethod
22
42
  def new: (*untyped, **untyped) -> _ActionInstance
@@ -39,13 +59,17 @@ module Mu
39
59
  def before_hooks: () -> ::Array[untyped]
40
60
  def after_hooks: () -> ::Array[untyped]
41
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
42
65
  end
43
66
 
44
67
  class FailureError < StandardError
45
68
  attr_reader error: untyped
46
- attr_reader meta: ::Hash[untyped, untyped]
69
+ attr_reader details: ::Hash[Symbol, untyped]
70
+ attr_reader failure: Failure?
47
71
 
48
- def initialize: (untyped error, ?meta: ::Hash[untyped, untyped]) -> void
72
+ def initialize: (untyped error, ?details: ::Hash[Symbol, untyped], ?failure: Failure?) -> void
49
73
  end
50
74
 
51
75
  class Result < Literal::Struct
@@ -64,17 +88,26 @@ module Mu
64
88
 
65
89
  class Failure < Result
66
90
  attr_reader error: untyped
91
+ attr_reader details: ::Hash[Symbol, untyped]
67
92
 
68
93
  def initialize: (*untyped, **untyped) -> void
69
94
  def success?: () -> false
70
95
  def failure?: () -> true
71
96
  end
72
97
 
73
- module Initializer
98
+ module Initializer : _ActionInstance
99
+ @meta: ::Hash[untyped, untyped]
100
+
74
101
  def initialize: (*untyped, **untyped) -> void
75
102
  def initialize_meta: () -> void
76
- def meta: () -> ::Hash[untyped, untyped]
77
- def self.literal_properties: () -> ::Array[untyped]
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?
78
111
  end
79
112
 
80
113
  module ClassMethods
@@ -89,6 +122,14 @@ module Mu
89
122
  def call: (*untyped, **untyped) -> untyped
90
123
  def call!: (*untyped, **untyped) -> untyped
91
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
92
133
  def register_hook: (untyped collection, untyped method_names, ::Proc? block, name: Symbol) -> untyped
93
134
  def normalize_hook_inputs: (untyped method_names, ::Proc? block, name: Symbol) -> untyped
94
135
  def ensure_valid_hook_inputs: (untyped method_names, ::Proc? block, name: Symbol) -> void
@@ -97,11 +138,13 @@ module Mu
97
138
  def new: (*untyped, **untyped) -> _ActionInstance
98
139
  end
99
140
 
100
- def Success: (untyped value) -> Success
141
+ def Success: (?untyped value) -> Success
101
142
  def Failure: (untyped error, **untyped) -> bot
102
143
  def run: () -> Result
103
144
  def run!: () -> Result
104
- def result_class: () -> ::Class
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
105
148
  def with_hooks: () { () -> Result } -> Result
106
149
  def run_before_hooks: () -> ::Array[untyped]
107
150
  def run_after_hooks: () -> ::Array[untyped]
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: mu-action
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nicolas Buduroi
@@ -31,29 +31,17 @@ executables: []
31
31
  extensions: []
32
32
  extra_rdoc_files: []
33
33
  files:
34
- - ".rspec"
35
- - ".rubocop.yml"
36
- - AGENTS.md
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
- - Steepfile
45
- - lib/guard/steep.rb
46
37
  - lib/mu/action.rb
47
38
  - lib/mu/action/version.rb
48
- - sig/kernel.rbs
49
- - sig/literal.rbs
50
39
  - sig/mu/action.rbs
51
40
  homepage: https://github.com/budu/mu-action
52
41
  licenses:
53
42
  - MIT
54
43
  metadata:
55
44
  allowed_push_host: https://rubygems.org
56
- homepage_uri: https://github.com/budu/mu-action
57
45
  source_code_uri: https://github.com/budu/mu-action
58
46
  changelog_uri: https://github.com/budu/mu-action/blob/main/CHANGELOG.md
59
47
  rubygems_mfa_required: 'true'
@@ -64,14 +52,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
64
52
  requirements:
65
53
  - - ">="
66
54
  - !ruby/object:Gem::Version
67
- version: 3.1.0
55
+ version: 3.2.0
68
56
  required_rubygems_version: !ruby/object:Gem::Requirement
69
57
  requirements:
70
58
  - - ">="
71
59
  - !ruby/object:Gem::Version
72
60
  version: '0'
73
61
  requirements: []
74
- rubygems_version: 3.7.2
62
+ rubygems_version: 4.0.3
75
63
  specification_version: 4
76
64
  summary: Modern interactor pattern with type safety and metadata tracking
77
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/AGENTS.md DELETED
@@ -1,32 +0,0 @@
1
- # Repository Guidelines
2
-
3
- ## Project Structure & Module Organization
4
- - `lib/mu/action` holds the core interactor implementation; mirror this layout when adding new components so `lib/mu/action/foo.rb` pairs with `Mu::Action::Foo`.
5
- - `spec/` mirrors the library structure with RSpec examples; add a matching `_spec.rb` file for every public entry point.
6
- - `sig/` provides RBS signatures that keep types honest—update them alongside code changes.
7
- - `bin/` hosts contributor tooling (`check`, `console`, `test_readme_examples`); treat `readme_examples.rb` as generated output.
8
-
9
- ## Build, Test, and Development Commands
10
- - `bin/check` aggregates lint, spec, and README example runs for a pre-PR smoke test. Use this instead of `rake`.
11
- - `bundle exec rspec spec/mu/action/hook_spec.rb` executes targeted tests; leave focused specs checked in only when necessary.
12
- - `bundle exec rubocop` enforces style; let it guide formatting instead of manual tweaks.
13
- - `bundle exec steep check` validates Steep signatures against implementation.
14
- - `bin/test_readme_examples --extract-only` regenerates `readme_examples.rb` after documentation updates.
15
-
16
- ## Coding Style & Naming Conventions
17
- - Target Ruby 3.1 with two-space indentation and trailing commas only when required.
18
- - RuboCop enforces double-quoted strings and general style—prefer fixes via `bundle exec rubocop -A` over manual edits.
19
- - Match class and module names to their file paths (e.g., `Mu::Action::Result` lives in `lib/mu/action/result.rb`), and keep method names snake_case verbs.
20
- - Favor small, composable interactors with explicit `prop` declarations and `Success`/`Failure` returns to stay idiomatic.
21
-
22
- ## Testing Guidelines
23
- - Write RSpec examples that describe observable behavior; structure files as `describe Mu::Action::Feature` with nested `context` blocks.
24
- - Cover both success and failure branches, including metadata expectations when hooks mutate state.
25
- - Keep factories lightweight—inline doubles or `let` helpers beat global fixtures for clarity.
26
- - Run `bundle exec rspec` locally and ensure README examples still execute via `bin/check` whenever documentation changes.
27
-
28
- ## Commit & Pull Request Guidelines
29
- - Follow the existing Conventional Commit style (`feat:`, `chore:`, `docs:`) visible in `git log --oneline`.
30
- - Keep commits scoped to a single concern and include any signature or README updates in the same change.
31
- - Open pull requests with a brief summary, linked issues (if any), and mention any developer-facing changes or new scripts.
32
- - State that `bin/check` passes; add screenshots or console snippets only when behavior changes are user-visible.
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,34 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "guard/steep"
4
-
5
- guard :rubocop, cli: "--format progress" do
6
- watch(/.+\.rb$/)
7
- watch(%r{(?:.+/)?\.rubocop(?:_todo)?\.yml$}) { File.dirname(_1[0]) }
8
- end
9
-
10
- guard :steep, command: "bundle exec steep check" do
11
- watch("Steepfile")
12
- watch(%r{^sig/.+\.rbs$})
13
- watch(%r{^lib/.+\.rb$})
14
- end
15
-
16
- guard :rspec, cmd: "bundle exec rspec" do
17
- require "guard/rspec/dsl"
18
- dsl = Guard::RSpec::Dsl.new(self)
19
-
20
- # Ruby files
21
- ruby = dsl.ruby
22
- dsl.watch_spec_files_for(ruby.lib_files)
23
-
24
- # RSpec files
25
- rspec = dsl.rspec
26
- watch(rspec.spec_helper) { rspec.spec_dir }
27
- watch(rspec.spec_support) { rspec.spec_dir }
28
- watch(rspec.spec_files)
29
-
30
- # Watch lib files
31
- watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
32
- watch(%r{^lib/mu/action/(.+)\.rb$}) { "spec/mu/action_spec.rb" }
33
- watch(%r{^lib/mu/action\.rb$}) { Dir["spec/*"] }
34
- 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]
data/Steepfile DELETED
@@ -1,8 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- target :lib do
4
- signature "sig"
5
- check "lib"
6
-
7
- configure_code_diagnostics(Steep::Diagnostic::Ruby.default)
8
- end
data/lib/guard/steep.rb DELETED
@@ -1,29 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "guard/plugin"
4
-
5
- # steep:ignore:start
6
- module Guard
7
- # Guard plugin that runs Steep type checking whenever files change.
8
- class Steep < Plugin
9
- def initialize(options = {})
10
- super
11
- @command = options.fetch(:command, "bundle exec steep check")
12
- end
13
-
14
- def start = run_steep
15
- def run_all = run_steep
16
- def run_on_additions(_paths) = run_steep
17
- def run_on_modifications(_paths) = run_steep
18
- def run_on_removals(_paths) = run_steep
19
-
20
- private
21
-
22
- def run_steep
23
- UI.info "📐 Running Steep..."
24
- success = system(@command)
25
- UI.error "Steep check failed" unless success
26
- end
27
- end
28
- end
29
- # steep:ignore:end
data/sig/kernel.rbs DELETED
@@ -1,3 +0,0 @@
1
- module Kernel
2
- def instance_exec: (*untyped) { (*untyped) -> untyped } -> untyped
3
- end
data/sig/literal.rbs DELETED
@@ -1,13 +0,0 @@
1
- module Literal
2
- module Properties
3
- def prop: (Symbol, untyped, *untyped, ?default: untyped) -> untyped
4
- def _Any: () -> untyped
5
- end
6
-
7
- class Struct
8
- extend Properties
9
-
10
- def self.prop: (Symbol, untyped, *untyped, ?default: untyped) -> untyped
11
- def self.literal_properties: () -> ::Array[untyped]
12
- end
13
- end