在编写模块化、表达力强且顺序逻辑的代码时,以简单而强大的方式表示用例。
Represent use cases in a simple and powerful way: write modular, expressive, sequentially logical code.
Leia este README em português
[!IMPORTANT] No breaking API changes — ever. From here on,
u-case's public API and runtime contracts won't break. The gem's role is to remain a stable, backward-compatible foundation for the projects that already depend on it. Any "next major" rethink of the abstractions belongs insolid-process(a redesign that applies what we've learned sinceu-casewas created), not in a futureu-case6.x.Major version bumps signal only that a Ruby or Rails version was dropped from the supported matrix — per SemVer, a dependency-floor change. Your code keeps working.
See the full statement on issue #131.
That's the whole shape: attributes, a call! method, Success(...) or Failure(...). Everything else in this README is a way to make that shape easier to compose, validate, observe, and transact.
…Need a structured input? Declare attributes with a block — child attributes inherit the host's feature mix (see Going further with u-attributes):
class CreateOrder { it.is?(String) && it.match?(/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/) }
attribute :uuid, accept: UUID
attribute :customer do
attribute :name, accept: String
attribute :email, accept: String
end
def call!
transaction do
customer = Customer.create_or_find_by!(email: customer.email) { it.name = customer.name }
order = Order.create!(uuid:, customer_id: customer.id)
Success result: { customer:, order: }
end
end
endNeed atomic, multi-step work? Wrap a whole flow in a transaction with one kwarg, or scope an ActiveRecord::Base.transaction to a single call!:
…ruby
attribute :title, accept: -> { it.is_a?(String) && !it.empty? } Slugify.call(title: 'Hello').on_success { puts it[:slug] }
attribute :title, accept: ->(value) { value.is_a?(String) && !value.empty? } Slugify.call(title: 'Hello').on_success { |data| puts data[:slug] }
**[Hash value omission](https://docs.ruby-lang.org/en/3.1/syntax/literals_rdoc.html#label-Hash+Literals)** — Ruby 3.1+
When a hash key matches an in-scope local variable (or method) name, you can drop the value:
```ruby
slug = 'hello-world'
# Modern (Ruby >= 3.1)
Success(result: { slug: })
# Classic — equivalent on every supported Ruby
Success(result: { slug: slug })
…
ruby
gem 'u-case', '~> 5.0'Then run bundle, or install it yourself with gem install u-case.
class ValidateEmail true
result.data # => { address: "ada@example.com" }
bad_result = ValidateEmail.call(address: 'not-an-email')
bad_result.failure? # => true
bad_result.data # => { message: "`address` must be a valid email" }The object returned by .call is a Micro::Case::Result — the subject of the next section.
Micro::Case::Strict requires every declared attribute to be passed on .call. Missing keywords raise ArgumentError:
class FormatGreeting ArgumentError (missing keyword: :time_of_day)Use it when you want missing input to fail loudly instead of letting time_of_day arrive as nil and produce a silently wrong message.
Micro::Case::Safe is another base class. It auto-intercepts any exception raised inside call! and turns it into a Failure with type: :exception. The exception itself is available under result[:exception]:
require 'json'
require 'logger'
AppLogger = Logger.new(STDOUT)
class ParseJsonPayload :exception
result.data # => { exception: # }
result[:exception].is_a?(JSON::ParserError) # => true
result.on_failure(:exception) do
AppLogger.error(it[:exception].message)
endTo branch on the exception class, use case/when (or pattern matching) inside the hook:
result.on_failure(:exception) do |data, use_case|
case (e = data[:exception])
when JSON::ParserError then AppLogger.error("malformed JSON: #{e.message}")
else AppLogger.debug("#{use_case.class.name} raised #{e.class}")
end
endYou can still rescue an exception explicitly inside a Safe use case — see these test examples.
A safe flow intercepts exceptions in any of its steps:
module Users
Create = Micro::Cases.safe_flow([
ProcessParams,
ValidateParams,
Persist,
SendToCRM
])
# Or as a class:
class Create Both the typed `on_exception(JSON::ParserError)` and the catch-all `on_exception` fire — like all u-case hooks, every match runs in declaration order (see [Result hooks](#result-hooks)).
##### Opting out of Safe
The Safe mechanism is opinionated: any unhandled exception becomes a `:exception` failure. That convenience can fragment a codebase — some exceptions handled by `rescue` inside `call!`, others by `on_exception` later. If you want a single explicit convention (plain `rescue` only), disable Safe entirely:
```ruby
Micro::Case.config do |config|
config.disable_safe_features = true
endWhen set to true, the following raise Micro::Case::Error::SafeFeaturesDisabled:
Micro::Case::SafeMicro::Cases.safe_flow(...)Micro::Case::Result#on_exceptionA Micro::Case::Result carries the use case's output. The methods you'll reach for most:
#success? / #failure? — boolean discriminants.#type — Symbol describing the result (:ok, :error, :exception, or any custom type).#data — the result data hash. #value is a backwards-compatible alias.#[], #values_at, #fetch, #fetch_values, #keys, #key?, #value?, #slice — Hash-like access into #data.#use_case — the use case instance that produced the result (handy for failure diagnostics inside a flow).#on_success / #on_failure / #on_exception — hooks for branching on the result.#then — apply another use case (or lambda / method / symbol) to a successful result; the basis for internal steps and dynamic continuations.#transitions — array of every step that produced this result; see inspecting execution.Result objects also support pattern matching and array decomposition.
Every result carries a type. The defaults:
:ok — for Success(...).:error — for Failure(...) whose payload is a Hash.:exception — for Failure(result: some_exception) (an Exception instance).class FetchUser exception
Failure result: exception
end
end
FetchUser.call(id: 1).type # => :ok
FetchUser.call(id: 'x').type # => :error
FetchUser.call(id: 999_999).type # => :exception (ActiveRecord::RecordNotFound)Pass a symbol as the first argument of Success(...) / Failure(...) to give the result a custom type:
class MergeTags :invalid_inputPassing only the symbol (no result:) is allowed — the data becomes { => true }. This shape is useful as a quick discriminant inside a flow:
def call!
return Failure(:invalid_input) unless primary.is_a?(Array) && secondary.is_a?(Array)
Success result: { tags: (primary + secondary).uniq }
end
# result.data => { invalid_input: true }Use the results do |on| ... end macro to declare which result types your use case can produce and which keys each one requires. Calls that use an undeclared type raise Micro::Case::Error::UnexpectedResultType; calls that omit a declared required key raise Micro::Case::Error::MissingResultKeys.
class PublishPost { post: # }
PublishPost.call(post: empty_post).type # => :missing_content
PublishPost.call(post: already_live_post).type # => :already_publishedA type passed without result: declares it with no required keys (any payload — including the implicit { type => true } from Failure(:my_type) — is accepted). With result: [:key1, :key2], those keys must be present in the result hash; extra keys are fine.
…The use case responsible for the result is always available as the hook's second block argument.
Without an explicit type, the block receives the whole result, so you can branch with a case statement:
ChangePassword
.call(user: ada, new_password: 'short')
.on_failure do |result, use_case|
case result.type
when :weak then raise ArgumentError, 'password too short'
when :reused then raise ArgumentError, 'password recently used'
else raise NotImplementedError
end
endIf the same hook is declared multiple times, every match fires:
calls = 0
result = ChangePassword.call(user: ada, new_password: 'long-enough-1')
result
.on_success { calls += 1 }
.on_success { calls += 1 }
.on_success(:ok) { calls += 1 }
.on_success(:ok) { calls += 1 }
calls # => 4Micro::Case::Result implements deconstruct and deconstruct_keys, so Ruby case/in works out of the box (Ruby ≥ 2.7):
case result
in { success: _, data: { number: Numeric => number } }
puts "got #{number}"
in { failure: :invalid_attributes, data: { invalid_attributes: errors } }
warn "bad input: #{errors.keys.join(", ")}"
in { failure: :exception, data: { exception: } }
warn "boom: #{exception.message}"
endThe hash patterns expose these keys:
| Key | Present on | Value |
|---|---|---|
success: |
success only | the result type (e.g. :ok) |
failure: |
failure only | the result type (e.g. :invalid_attributes) |
type: |
always | the result type |
data: |
always | the result data hash |
result: |
always | alias of data: (matches the Success(result: …) keyword at the call site) |
use_case: |
always | the use case instance that produced the result |
transitions: |
always | the result transitions array |
Result#deconstruct returns a three-element array [status, type, data] where status is :success or :failure, so array patterns can use the status as a discriminant — mirroring how libraries with separate Success / Failure classes are pattern-matched, even though Micro::Case::Result is a single class:
case result
in [:success, :ok, { number: Integer => n }]
n
in [:failure, :invalid_attributes, { invalid_attributes: errors }]
# ...
in [:failure, :exception, { exception: }]
# ...
end
Result#to_aryis unchanged and still returns[data, type](used by
暂无开放 Issues,或尚未同步最近议题。