Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
U

u-case

> 编程语言
Open source

Represent use cases in a simple and powerful way while writing modular, expressive and sequentially logical code.

550 stars0 likes1 views
WebsiteGitHub

About

Represent use cases in a simple and powerful way while writing modular, expressive and sequentially logical code.

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 in solid-process (a redesign that applies what we've learned since u-case was created), not in a future u-case 6.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.

Quick start

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):

ruby
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
end

Need 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

Modern (Ruby >= 3.4) — what you'll see throughout this README

attribute :title, accept: -> { it.is_a?(String) && !it.empty? } Slugify.call(title: 'Hello').on_success { puts it[:slug] }

Classic — equivalent on every supported Ruby

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.

Usage

Defining a use case

The basics

ruby
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.

Strict mode — required attributes

Micro::Case::Strict requires every declared attribute to be passed on .call. Missing keywords raise ArgumentError:

ruby
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.

Safe mode — capturing exceptions

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]:

ruby
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)
end

To branch on the exception class, use case/when (or pattern matching) inside the hook:

ruby
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
end

You can still rescue an exception explicitly inside a Safe use case — see these test examples.

Safe flows

A safe flow intercepts exceptions in any of its steps:

ruby
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
end

When set to true, the following raise Micro::Case::Error::SafeFeaturesDisabled:

  • subclassing Micro::Case::Safe
  • calling Micro::Cases.safe_flow(...)
  • calling Micro::Case::Result#on_exception

⬆️ Back to Top

Working with results

A Micro::Case::Result carries the use case's output. The methods you'll reach for most:

The Result API

  • #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.

Default and custom result types

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).
ruby
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:

ruby
class MergeTags  :invalid_input

Passing only the symbol (no result:) is allowed — the data becomes { => true }. This shape is useful as a quick discriminant inside a flow:

ruby
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 }

Result contracts

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.

ruby
class PublishPost  { post: # }
PublishPost.call(post: empty_post).type        # => :missing_content
PublishPost.call(post: already_live_post).type # => :already_published

A 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:

ruby
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
  end

If the same hook is declared multiple times, every match fires:

ruby
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 # => 4

Pattern matching

Micro::Case::Result implements deconstruct and deconstruct_keys, so Ruby case/in works out of the box (Ruby ≥ 2.7):

ruby
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}"
end

The 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:

ruby
case result
in [:success, :ok, { number: Integer => n }]
  n
in [:failure, :invalid_attributes, { invalid_attributes: errors }]
  # ...
in [:failure, :exception, { exception: }]
  # ...
end

Result#to_ary is unchanged and still returns [data, type] (used by

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyapplication-flowbusiness-logiccommandinteractors

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言