Represent use cases in a simple and powerful way while writing modular, expressive and sequentially logical code.
The main project goals are:
- Easy to use and easy to learn (input >> process >> output).
- Promote immutability (transforming data instead of modifying it) and data integrity.
- No callbacks (ex: before, after, around) to avoid code indirections that could compromise the state and understanding of application flows.
- Solve complex business logic, by allowing the composition of use cases (flow creation).
- Be fast and optimized (Check out the benchmarks section).
Note: Check out the repo https://github.com/serradura/from-fat-controllers-to-use-cases to see a Rails application that uses this gem to handle its business logic.
Documentation <!-- omit in toc -->
| Version | Documentation |
|---|---|
| unreleased | https://github.com/serradura/u-case/blob/main/README.md |
| 5.6.0 | https://github.com/serradura/u-case/blob/v5.x/README.md |
| 4.5.1 | https://github.com/serradura/u-case/blob/v4.x/README.md |
Note: Você entende português? 🇧🇷 🇵🇹 Verifique o README traduzido em pt-BR.
Table of Contents <!-- omit in toc -->
- Compatibility
- Dependencies
- Installation
- Usage
Micro::Case- How to define a use case?Micro::Case::Result- What is a use case result?- What are the default result types?
- How to define custom result types?
- Is it possible to define a custom type without a result data?
- How to declare a results contract?
- How to use the result hooks?
- Why the hook usage without a defined type exposes the result itself?
- What happens if a result hook was declared multiple times?
- How to use the
Micro::Case::Result#thenmethod? - Internal steps — building a flow inline inside
call! Micro::Cases::Flow- How to compose use cases?- Is it possible to compose a flow with other flows?
- Is it possible a flow accumulates its input and merges each success result to use as the argument of the next use cases?
- How to understand what is happening during a flow execution?
- Is it possible to declare a flow that includes the use case itself as a step?
- How to run a use case or flow inside a database transaction?
Micro::Case::Strict- What is a strict use case?Micro::Case::Safe- Is there some feature to auto handle exceptions inside of a use case or flow?Micro::Cases::Safe::FlowMicro::Case::Result#on_exception- Opting out of the safe mechanism
- Validating attributes with
accept:/reject: u-case/with_activemodel_validation- How to validate the use case attributes?- If I enabled the auto validation, is it possible to disable it only in specific use cases?
Kind::Validator
Micro::Case.config- Benchmarks
- Examples
- Development
- Contributing
- License
- Code of Conduct
Compatibility
| u-case | branch | ruby | activemodel | u-attributes |
|---|---|---|---|---|
| unreleased | main | >= 2.7 | >= 6.0 | >= 2.8, < 4.0 |
| 5.6.0 | v5.x | >= 2.7 | >= 6.0 | >= 2.8, < 4.0 |
| 5.1.0 | v5.x | >= 2.7 | >= 6.0 | >= 2.7, < 4.0 |
| 4.5.1 | v4.x | >= 2.2.0 | >= 3.2, <= 8.1 | >= 2.7, < 3.0 |
This library is tested (CI matrix) against:
| Ruby / Rails | 6.0 | 6.1 | 7.0 | 7.1 | 7.2 | 8.0 | 8.1 | Edge |
|---|---|---|---|---|---|---|---|---|
| 2.7 | ✅ | ✅ | ✅ | ✅ | ||||
| 3.0 | ✅ | ✅ | ✅ | ✅ | ||||
| 3.1 | ✅ | ✅ | ✅ | |||||
| 3.2 | ✅ | ✅ | ✅ | ✅ | ||||
| 3.3 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ||
| 3.4 | ✅ | ✅ | ✅ | ✅ | ||||
| 4.x | ✅ | ✅ | ||||||
| Head | ✅ | ✅ |
Note: The activemodel is an optional dependency, this module can be enabled to validate the use cases' attributes.
Dependencies
kindgem.A simple type system (at runtime) for Ruby.
It is used to validate some internal u-case's methods input. This gem also exposes an
ActiveModel validatorwhen requiring theu-case/with_activemodel_validationmodule, or when theMicro::Case.configwas used to enable it.u-attributesgem.This gem allows defining read-only attributes, that is, your objects will have only getters to access their attributes data. It is used to define the use case attributes.
Installation
Add this line to your application's Gemfile:
gem 'u-case', '~> 5.0'
And then execute:
$ bundle
Or install it yourself as:
$ gem install u-case
Usage
Micro::Case - How to define a use case?
class Multiply < Micro::Case
# 1. Define its input as attributes
attributes :a, :b
# 2. Define the method `call!` with its business logic
def call!
# 3. Wrap the use case output using the `Success(result: *)` or `Failure(result: *)` methods
if a.is_a?(Numeric) && b.is_a?(Numeric)
Success result: { number: a * b }
else
Failure result: { message: '`a` and `b` attributes must be numeric' }
end
end
end
#========================#
# Performing an use case #
#========================#
# Success result
result = Multiply.call(a: 2, b: 2)
result.success? # true
result.data # { number: 4 }
# Failure result
bad_result = Multiply.call(a: 2, b: '2')
bad_result.failure? # true
bad_result.data # { message: "`a` and `b` attributes must be numeric" }
# Note:
# ----
# The result of a Micro::Case.call is an instance of Micro::Case::Result
Micro::Case::Result - What is a use case result?
A Micro::Case::Result stores the use cases output data. These are their main methods:
#success?returns true if is a successful result.#failure?returns true if is an unsuccessful result.#use_casereturns the use case responsible for it. This feature is handy to handle a flow failure (this topic will be covered ahead).#typea Symbol which gives meaning for the result, this is useful to declare different types of failures or success.#datathe result data itself.#[]and#values_atare shortcuts to access the#datavalues.#fetchand#fetch_valuesare another way of accessing values of the result data, but raises aKeyErrorif the one of the keys are not present in the result.#keysreturns an array of keys present in the result data.#key?returnstrueif the key is present in#data.#value?returnstrueif the given value is present in#data.#slicereturns a new hash that includes only the given keys. If the given keys don't exist, an empty hash is returned.#on_successor#on_failureare hook methods that help you to define the application flow.#thenthis method will allow applying a new use case if the current result was a success. The idea of this feature is to allow the creation of dynamic flows.#transitionsreturns an array with all of transformations wich a result has during a flow.
Note: for backward compatibility, you could use the
#valuemethod as an alias of#datamethod.
What are the default result types?
Every result has a type, and these are their default values:
:okwhen success:erroror:exceptionwhen failures
class Divide < Micro::Case
attributes :a, :b
def call!
if invalid_attributes.empty?
Success result: { number: a / b }
else
Failure result: { invalid_attributes: invalid_attributes }
end
rescue => exception
Failure result: exception
end
private def invalid_attributes
attributes.select { |_key, value| !value.is_a?(Numeric) }
end
end
# Success result
result = Divide.call(a: 2, b: 2)
result.type # :ok
result.data # { number: 1 }
result.success? # true
result.use_case # #<Divide:0x0000 @__attributes={"a"=>2, "b"=>2}, @a=2, @b=2, @__result=...>
# Failure result (type == :error)
bad_result = Divide.call(a: 2, b: '2')
bad_result.type # :error
bad_result.data # { invalid_attributes: { "b"=>"2" } }
bad_result.failure? # true
bad_result.use_case # #<Divide:0x0000 @__attributes={"a"=>2, "b"=>"2"}, @a=2, @b="2", @__result=...>
# Failure result (type == :exception)
err_result = Divide.call(a: 2, b: 0)
err_result.type # :exception
err_result.data # { exception: <ZeroDivisionError: divided by 0> }
err_result.failure? # true
err_result.use_case # #<Divide:0x0000 @__attributes={"a"=>2, "b"=>0}, @a=2, @b=0, @__result=#<Micro::Case::Result:0x0000 @use_case=#<Divide:0x0000 ...>, @type=:exception, @value=#<ZeroDivisionError: divided by 0>, @success=false>
# Note:
# ----
# Any Exception instance which is wrapped by
# the Failure(result: *) method will receive `:exception` instead of the `:error` type.
How to define custom result types?
Answer: Use a symbol as the argument of Success(), Failure() methods and declare the result: keyword to set the result data.
class Multiply < Micro::Case
attributes :a, :b
def call!
if a.is_a?(Numeric) && b.is_a?(Numeric)
Success result: { number: a * b }
else
Failure :invalid_data, result: {
attributes: attributes.reject { |_, input| input.is_a?(Numeric) }
}
end
end
end
# Success result
result = Multiply.call(a: 3, b: 2)
result.type # :ok
result.data # { number: 6 }
result.success? # true
# Failure result
bad_result = Multiply.call(a: 3, b: '2')
bad_result.type # :invalid_data
bad_result.data # { attributes: {"b"=>"2"} }
bad_result.failure? # true
Is it possible to define a custom type without a result data?
Answer: Yes, it is possible. But this will have special behavior because the result data will be a hash with the given type as the key and true as its value.
class Multiply < Micro::Case
attributes :a, :b
def call!
if a.is_a?(Numeric) && b.is_a?(Numeric)
Success result: { number: a * b }
else
Failure(:invalid_data)
end
end
end
result = Multiply.call(a: 2, b: '2')
result.failure? # true
result.data # { :invalid_data => true }
result.type # :invalid_data
result.use_case.attributes # {"a"=>2, "b"=>"2"}
# Note:
# ----
# This feature is handy to handle failures in a flow
# (this topic will be covered ahead).
How to declare a results contract?
Answer: Use the results do |on| ... end macro to declare which result types your use case can return, and which keys each one requires. When a contract is declared, Success(...) / Failure(...) calls that use an undeclared type raise Micro::Case::Error::UnexpectedResultType, and calls that omit a declared required key raise Micro::Case::Error::MissingResultKeys.
class Divide < Micro::Case
attributes :a, :b
results do |on|
on.failure(:attributes_must_be_numbers)
on.failure(:division_by_zero)
on.success(result: [:division])
end
def call!
return Failure(:attributes_must_be_numbers) unless Kind.of?(Numeric, a, b)
return Failure(:division_by_zero) if b == 0
Success result: { division: a / b }
end
end
Divide.call(a: 10, b: 2).data # => { division: 5 }
Divide.call(a: 10, b: 0).type # => :division_by_zero
Divide.call(a: 'x', b: 2).type # => :attributes_must_be_numbers
A type passed to on.success / on.failure without a result: argument declares the type with no required keys (any payload — including the implicit { type => true } from Failure(:my_type) — is accepted). When result: [:key1, :key2] is given, those keys must be present in the result hash; extra keys are allowed.
class Wrong < Micro::Case
results do |on|
on.success(result: [:value])
on.failure(:known)
end
def call!
Success(:other, result: { value: 1 }) # raises Micro::Case::Error::UnexpectedResultType
# Success(result: { wrong: 1 }) # raises Micro::Case::Error::MissingResultKeys
# Failure(:other) # raises Micro::Case::Error::UnexpectedResultType
end
end
Notes:
- Use cases without a
resultsblock keep their previous unrestricted behavior — the contract is opt-in. - Subclasses inherit the parent's contract.
- Rescued exceptions in
Micro::Case::Safe(which produceFailure(result: exception)automatically) bypass the contract.
How to use the result hooks?
As mentioned earlier, the Micro::Case::Result has two methods to improve the application flow control. They are: #on_success, on_failure.
The examples below show how to use them:
class Double < Micro::Case
attribute :number
def call!
return Failure :invalid, result: { msg: 'number must be a numeric value' } unless number.is_a?(Numeric)
return Failure :lte_zero, result: { msg: 'number must be greater than 0' } if number <= 0
Success result: { number: number * 2 }
end
end
#================================#
# Printing the output if success #
#================================#
Double
.call(number: 3)
.on_success { |result| p result[:number] }
.on_failure(:invalid) { |result| raise TypeError, result[:msg] }
.on_failure(:lte_zero) { |result| raise ArgumentError, result[:msg] }
# The output will be:
# 6
#=============================#
# Raising an error if failure #
#=============================#
Double
.call(number: -1)
.on_success { |result| p result[:number] }
.on_failure { |_result, use_case| puts "#{use_case.class.name} was the use case responsible for the failure" }
.on_failure(:invalid) { |result| raise TypeError, result[:msg] }
.on_failure(:lte_zero) { |result| raise ArgumentError, result[:msg] }
# The outputs will be:
#
# 1. It will print the message: Double was the use case responsible for the failure
# 2. It will raise the exception: ArgumentError (the number must be greater than 0)
# Note:
# ----
# The use case responsible for the result will always be accessible as the second hook argument
Why the hook usage without a defined type exposes the result itself?
Answer: To allow you to define how to handle the program flow using some conditional statement like an if or case when.
class Double < Micro::Case
attribute :number
def call!
return Failure(:invalid) unless number.is_a?(Numeric)
return Failure :lte_zero, result: attributes(:number) if number <= 0
Success result: { number: number * 2 }
end
end
Double
.call(number: -1)
.on_failure do |result, use_case|
case result.type
when :invalid then raise TypeError, "number must be a numeric value"
when :lte_zero then raise ArgumentError, "number `#{result[:number]}` must be greater than 0"
else raise NotImplementedError
end
end
# The output will be an exception:
#
# ArgumentError (number `-1` must be greater than 0)
Note: The same that was did in the previous examples could be done with
#on_successhook!
Using decomposition to access the result data and type
The syntax to decompose an Array can be used in assignments and in method/block arguments. If you doesn't know it, check out the Ruby doc.
# The object exposed in the hook without a type is a Micro::Case::Result and it can be decomposed. e.g:
Double
.call(number: -2)
.on_failure do |(data, type), use_case|
case type
when :invalid then raise TypeError, 'number must be a numeric value'
when :lte_zero then raise ArgumentError, "number `#{data[:number]}` must be greater than 0"
else raise NotImplementedError
end
end
# The output will be the exception:
#
# ArgumentError (the number `-2` must be greater than 0)
Note: The same that was did in the previous examples could be done with
#on_successhook!
Using pattern matching to destructure a result
Micro::Case::Result implements deconstruct and deconstruct_keys, so Ruby's case/in pattern matching works out of the box (requires Ruby >= 2.7).
result = Divide.call(a: 10, b: 2)
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.}"
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 used at the creation site) |
use_case: |
always | the use case instance that produced the result |
transitions: |
always | the result transitions array |
Note: On the reader side,
Result#datais also accessible asResult#value(existing alias). On the pattern-matching side, thedata:key is also accessible asresult:— both refer to the same payload.
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
Note:
Result#to_aryis unchanged and still returns[data, type](used by multi-assignment, e.g.data, type = result). Ruby's pattern matching uses#deconstruct, so the two hooks intentionally return different shapes.
What happens if a result hook was declared multiple times?
Answer: The hook always will be triggered if it matches the result type.
class Double < Micro::Case
attributes :number
def call!
if number.is_a?(Numeric)
Success :computed, result: { number: number * 2 }
else
Failure :invalid, result: { msg: 'number must be a numeric value' }
end
end
end
result = Double.call(number: 3)
result.data # { number: 6 }
result[:number] * 4 # 24
accum = 0
result
.on_success { |result| accum += result[:number] }
.on_success { |result| accum += result[:number] }
.on_success(:computed) { |result| accum += result[:number] }
.on_success(:computed) { |result| accum += result[:number] }
accum # 24
result[:number] * 4 == accum # true
How to use the Micro::Case::Result#then method?
This method allows you to create dynamic flows, so, with it, you can add new use cases or flows to continue the result transformation. e.g:
class ForbidNegativeNumber < Micro::Case
attribute :number
def call!
return Success result: attributes if number >= 0
Failure result: attributes
end
end
class Add3 < Micro::Case
attribute :number
def call!
Success result: { number: number + 3 }
end
end
result1 =
ForbidNegativeNumber
.call(number: -1)
.then(Add3)
result1.data # {'number' => -1}
result1.failure? # true
# ---
result2 =
ForbidNegativeNumber
.call(number: 1)
.then(Add3)
result2.data # {'number' => 4}
result2.success? # true
Note: this method changes the
Micro::Case::Result#transitions.
What does happens when a Micro::Case::Result#then receives a block?
It will yields self (a Micro::Case::Result instance) to the block, and will return the output of the block instead of itself. e.g:
class Add < Micro::Case
attributes :a, :b
def call!
if Kind.of?(Numeric, a, b)
Success result: { sum: a + b }
else
Failure(:attributes_arent_numbers)
end
end
end
# --
success_result =
Add
.call(a: 2, b: 2)
.then { |result| result.success? ? result[:sum] : 0 }
puts success_result # 4
# --
failure_result =
Add
.call(a: 2, b: '2')
.then { |result| result.success? ? result[:sum] : 0 }
puts failure_result # 0
How to make attributes data injection using this feature?
Pass a Hash as the second argument of the Micro::Case::Result#then method.
Todo::FindAllForUser
.call(user: current_user, params: params)
.then(Paginate)
.then(Serialize::PaginatedRelationAsJson, serializer: Todo::Serializer)
.on_success { |result| render_json(200, data: result[:todos]) }
Internal steps — building a flow inline inside call!
Result#then (and its | pipe alias) is u-case's third way of
composing a flow, side by side with Micro::Cases.flow(...) and the
class-level flow ... macro. Instead of wiring sibling use cases
together, you keep the chain inside a single use case's call!:
each link is a method, lambda or another use case class; each link
returns a Micro::Case::Result; each link's Success data becomes
the next link's keyword arguments; and each link contributes a row to
result.transitions — just like a step in a top-level flow.
What Result#then (and |) accept
| Argument shape | Example |
|---|---|
Symbol (method name) |
result.then(:sum_a_and_b) |
Bound Method object |
result.then(method(:sum_a_and_b)) |
Lambda / Proc |
result.then(-> data { sum_a_and_b(**data) }) |
| Use case class | result.then(SumHalf) |
Symbol + Hash defaults |
result.then(:add, number: 3) |
| Block | `result.then { \ |
The connecting method must return a Micro::Case::Result. Anything
else raises Micro::Case::Error::UnexpectedResult — for example a
method that returns a plain Hash will be rejected with a message like
MyCase#method(:foo) must return an instance of Micro::Case::Result.
A minimal example
class SumHalf < Micro::Case
attribute :sum
def call!
Success :third_sum, result: { sum: sum + 0.5 }
end
end
class DoSomeSum < Micro::Case
attributes :a, :b
def call!
validate_numbers
.then(:sum_a_and_b)
.then(:add, number: 3)
.then(SumHalf)
end
private
def validate_numbers
Kind.of?(Numeric, a, b) ? Success(:valid) : Failure()
end
def sum_a_and_b
Success :first_sum, result: { sum: a + b }
end
def add(sum:, number:, **)
Success :second_sum, result: { sum: sum + number }
end
end
result = DoSomeSum.call(a: 1, b: 2)
result.success? # true
result.data # { sum: 6.5 }
result.transitions # 4 entries — see below
result.transitions for the call above:
[
{ use_case: { class: DoSomeSum, attributes: { a: 1, b: 2 } },
success: { type: :valid, result: { valid: true } },
accessible_attributes: [:a, :b] },
{ use_case: { class: DoSomeSum, attributes: { a: 1, b: 2 } },
success: { type: :first_sum, result: { sum: 3 } },
accessible_attributes: [:a, :b, :valid] },
{ use_case: { class: DoSomeSum, attributes: { a: 1, b: 2 } },
success: { type: :second_sum, result: { sum: 6 } },
accessible_attributes: [:a, :b, :valid, :number, :sum] },
{ use_case: { class: SumHalf, attributes: { sum: 6 } },
success: { type: :third_sum, result: { sum: 6.5 } },
accessible_attributes: [:a, :b, :valid, :number, :sum] }
]
Symbol-, method- and lambda-based links all run as the host use
case, so the first three transitions report class: DoSomeSum. Only
the SumHalf link, which is another use case class, contributes a
transition with a different use_case.class. The accessible_attributes
grows as each link's Success output is merged into the running data.
The | (pipe) alias
| is sugar for .then(...). The previous example becomes:
def call!
validate_numbers | :sum_a_and_b | :add | SumHalf
end
Both forms produce identical result.data and result.transitions.
Elixir-style chains with
it(Ruby ≥ 3.4): because Ruby 3.4 exposesitas the implicit first parameter of a block/lambda body, you can write a chain that reads almost exactly like Elixir's|>pipe. Each lambda receives the accumulated data hash asitand must still terminate in aSuccess(...)/Failure(...)call:def call! validate_something \ | -> { do_something_with(**it) } \ | -> { and_another_thing_with(**it) } endOn Ruby 2.7 – 3.3 (where
itis just an undefined identifier), use the portable explicit form->(data) { do_something_with(**data) }shown in the next section.
Lambda / Method forms
Lambdas (and bound Method objects) receive the accumulated data
positionally as a single Hash:
def call!
validate_numbers
.then(method(:sum_a_and_b))
.then(->(data) { add(**data, number: 3) })
.then(SumHalf)
end
Failure short-circuits the chain
Returning Failure(...) from any link halts the rest of the chain
immediately — exactly like a step in a top-level flow returning a
failure. The remaining .then(...) / | links are not invoked, and
the final result is the failure:
DoSomeSum.call(a: 1, b: '2')
# validate_numbers returns Failure() → :sum_a_and_b, :add and SumHalf
# never run. result.failure? == true, result.transitions has 1 entry.
Using an internal-step case inside an outer flow
A use case that composes internally with .then(...) is just a use
case, so you can drop it into any flow constructor:
SignUp = Micro::Cases.flow([
NormalizeParams,
DoSomeSum, # ← uses .then(:method) internally
EnqueueIndexingJob
])
The host class's internal transitions are interleaved with the outer
flow's leaf transitions in execution order. If DoSomeSum produces 4
internal transitions and the outer flow has 2 other leaf steps, the
final result.transitions has 6 entries.
Internal steps without transactions
By default — i.e. when neither the host class nor the outer flow uses
transaction: true — internal steps behave like any other code in
call!: side-effects made by earlier links persist even if a
later link returns Failure. The chain is interrupted, but anything
already written to the database stays written:
class CreateUserWithProfileInline < Micro::Case
attributes :name, :info
def call!
create_user
.then(:create_profile)
end
private
def create_user
user = User.create(name: name)
Success result: { user: user }
end
def create_profile(user:, **)
profile = UserProfile.create(user_id: user.id, info: info)
return Failure(:invalid_profile) if profile.errors.any?
Success result: { user: user, profile: profile }
end
end
CreateUserWithProfileInline.call(name: 'Rodrigo', info: '')
# create_user already INSERTed the user row; create_profile failed.
# user is persisted; profile is not. No automatic rollback.
If you need the partial side-effects to be undone, wrap the chain in
a transaction. Because internal steps are just another way of
expressing a flow (an internal flow), the transactional story is
exactly the one already documented in
How to run a use case or flow inside a database transaction?
below — the "Internal-step flows under transactions" subsection
there walks through both the inline transaction { ... } form and
the transaction: true flow form for an internal-step host case.
Note: See
test/micro/case/internal_steps/with_symbols_test.rb,with_methods_test.rbandwith_lambdas_test.rbfor full examples of each form, andtest/micro/cases/flow/internal_steps_in_flows_test.rbfor the interaction with flows and transactions (accumulation, transitions, rollback at every nesting level).
Micro::Cases::Flow - How to compose use cases?
We call as flow a composition of use cases. The main idea of this feature is to use/reuse use cases as steps of a new use case. e.g.
module Steps
class ConvertTextToNumbers < Micro::Case
attribute :numbers
def call!
if numbers.all? { |value| String(value) =~ /\d+/ }
Success result: { numbers: numbers.map(&:to_i) }
else
Failure result: { message: 'numbers must contain only numeric types' }
end
end
end
class Add2 < Micro::Case::Strict
attribute :numbers
def call!
Success result: { numbers: numbers.map { |number| number + 2 } }
end
end
class Double < Micro::Case::Strict
attribute :numbers
def call!
Success result: { numbers: numbers.map { |number| number * 2 } }
end
end
class Square < Micro::Case::Strict
attribute :numbers
def call!
Success result: { numbers: numbers.map { |number| number * number } }
end
end
end
#-------------------------------------------#
# Creating a flow using Micro::Cases.flow() #
#-------------------------------------------#
Add2ToAllNumbers = Micro::Cases.flow([
Steps::ConvertTextToNumbers,
Steps::Add2
])
result = Add2ToAllNumbers.call(numbers: %w[1 1 2 2 3 4])
result.success? # true
result.data # {:numbers => [3, 3, 4, 4, 5, 6]}
#-------------------------------#
# Creating a flow using classes #
#-------------------------------#
class DoubleAllNumbers < Micro::Case
flow Steps::ConvertTextToNumbers,
Steps::Double
end
DoubleAllNumbers.
call(numbers: %w[1 1 b 2 3 4]).
on_failure { |result| puts result[:message] } # "numbers must contain only numeric types"
When happening a failure, the use case responsible will be accessible in the result.
result = DoubleAllNumbers.call(numbers: %w[1 1 b 2 3 4])
result.failure? # true
result.use_case.is_a?(Steps::ConvertTextToNumbers) # true
result.on_failure do |, use_case|
puts "#{use_case.class.name} was the use case responsible for the failure" # Steps::ConvertTextToNumbers was the use case responsible for the failure
end
Is it possible to compose a flow with other flows?
Answer: Yes, it is possible.
module Steps
class ConvertTextToNumbers < Micro::Case
attribute :numbers
def call!
if numbers.all? { |value| String(value) =~ /\d+/ }
Success result: { numbers: numbers.map(&:to_i) }
else
Failure result: { message: 'numbers must contain only numeric types' }
end
end
end
class Add2 < Micro::Case::Strict
attribute :numbers
def call!
Success result: { numbers: numbers.map { |number| number + 2 } }
end
end
class Double < Micro::Case::Strict
attribute :numbers
def call!
Success result: { numbers: numbers.map { |number| number * 2 } }
end
end
class Square < Micro::Case::Strict
attribute :numbers
def call!
Success result: { numbers: numbers.map { |number| number * number } }
end
end
end
DoubleAllNumbers =
Micro::Cases.flow([Steps::ConvertTextToNumbers, Steps::Double])
SquareAllNumbers =
Micro::Cases.flow([Steps::ConvertTextToNumbers, Steps::Square])
DoubleAllNumbersAndAdd2 =
Micro::Cases.flow([DoubleAllNumbers, Steps::Add2])
SquareAllNumbersAndAdd2 =
Micro::Cases.flow([SquareAllNumbers, Steps::Add2])
SquareAllNumbersAndDouble =
Micro::Cases.flow([SquareAllNumbersAndAdd2, DoubleAllNumbers])
DoubleAllNumbersAndSquareAndAdd2 =
Micro::Cases.flow([DoubleAllNumbers, SquareAllNumbersAndAdd2])
SquareAllNumbersAndDouble
.call(numbers: %w[1 1 2 2 3 4])
.on_success { |result| p result[:numbers] } # [6, 6, 12, 12, 22, 36]
DoubleAllNumbersAndSquareAndAdd2
.call(numbers: %w[1 1 2 2 3 4])
.on_success { |result| p result[:numbers] } # [6, 6, 18, 18, 38, 66]
Note: You can blend any approach to create use case flows - examples.
Is it possible a flow accumulates its input and merges each success result to use as the argument of the next use cases?
Answer: Yes, it is possible! Look at the example below to understand how the data accumulation works inside of a flow execution.
module Users
class FindByEmail < Micro::Case
attribute :email
def call!
user = User.find_by(email: email)
return Success result: { user: user } if user
Failure(:user_not_found)
end
end
end
module Users
class ValidatePassword < Micro::Case::Strict
attributes :user, :password
def call!
return Failure(:user_must_be_persisted) if user.new_record?
return Failure(:wrong_password) if user.wrong_password?(password)
return Success result: attributes(:user)
end
end
end
module Users
Authenticate = Micro::Cases.flow([
FindByEmail,
ValidatePassword
])
end
Users::Authenticate
.call(email: 'somebody@test.com', password: 'password')
.on_success { |result| sign_in(result[:user]) }
.on_failure(:wrong_password) { render status: 401 }
.on_failure(:user_not_found) { render status: 404 }
First, let's see the attributes used by each use case:
class Users::FindByEmail < Micro::Case
attribute :email
end
class Users::ValidatePassword < Micro::Case
attributes :user, :password
end
As you can see the Users::ValidatePassword expects a user as its input. So, how does it receives the user?
Answer: It receives the user from the Users::FindByEmail success result!
And this is the power of use cases composition because the output of one step will compose the input of the next use case in the flow!
input >> process >> output
Note: Check out these test examples Micro::Cases::Flow and Micro::Cases::Safe::Flow to see different use cases having access to the data in a flow.
How to understand what is happening during a flow execution?
Use Micro::Case::Result#transitions!
Let's use the previous section example to ilustrate how to use this feature.
user_authenticated =
Users::Authenticate.call(email: 'rodrigo@test.com', password: user_password)
user_authenticated.transitions
[
{
:use_case => {
:class => Users::FindByEmail,
:attributes => { :email => "rodrigo@test.com" }
},
:success => {
:type => :ok,
:result => {
:user => #<User:0x00007fb57b1c5f88 @email="rodrigo@test.com" ...>
}
},
:accessible_attributes => [ :email, :password ]
},
{
:use_case => {
:class => Users::ValidatePassword,
:attributes => {
:user => #<User:0x00007fb57b1c5f88 @email="rodrigo@test.com" ...>
:password => "123456"
}
},
:success => {
:type => :ok,
:result => {
:user => #<User:0x00007fb57b1c5f88 @email="rodrigo@test.com" ...>
}
},
:accessible_attributes => [ :email, :password, :user ]
}
]
The example above shows the output generated by the Micro::Case::Result#transitions.
With it is possible to analyze the use cases' execution order and what were the given inputs ([:attributes]) and outputs ([:success][:result]) in the entire execution.
And look up the accessible_attributes property, it shows whats attributes are accessible in that flow step. For example, in the last step, you can see that the accessible_attributes increased because of the data flow accumulation.
Note: The
Micro::Case::Result#thenincrements theMicro::Case::Result#transitions.
Micro::Case::Result#transitions schema
[
{
use_case: {
class: <Micro::Case>,# Use case which was executed
attributes: <Hash> # (Input) The use case's attributes
},
[success:, failure:] => { # (Output)
type: <Symbol>, # Result type. Defaults:
# Success = :ok, Failure = :error/:exception
result: <Hash> # The data returned by the use case result
},
accessible_attributes: <Array>, # Properties that can be accessed by the use case's attributes,
# it starts with Hash used to invoke it and that will be incremented
# with the result values of each use case in the flow.
}
]
Is it possible disable the Micro::Case::Result#transitions?
Answer: Yes, it is! You can use the Micro::Case.config to do this. Link to this section.
Is it possible to declare a flow that includes the use case itself as a step?
Answer: Yes, it is! You can use self or the self.call! macro. e.g:
class ConvertTextToNumber < Micro::Case
attribute :text
def call!
Success result: { number: text.to_i }
end
end
class ConvertNumberToText < Micro::Case
attribute :number
def call!
Success result: { text: number.to_s }
end
end
class Double < Micro::Case
flow ConvertTextToNumber,
self.call!,
ConvertNumberToText
attribute :number
def call!
Success result: { number: number * 2 }
end
end
result = Double.call(text: '4')
result.success? # true
result[:number] # "8"
Note: This feature can be used with the Micro::Case::Safe. Checkout this test to see an example: https://github.com/serradura/u-case/blob/714c6b658fc6aa02617e6833ddee09eddc760f2a/test/micro/case/safe/with_inner_flow_test.rb
How to run a use case or flow inside a database transaction?
u-case ships with two complementary helpers for wrapping work in an
ActiveRecord::Base.transaction. Both opt-in — active_record is not
required by the gem, so you need to load ActiveRecord yourself (Rails
applications already do).
Micro::Case#transaction — inline transactions inside call!
Micro::Case#transaction (and Micro::Case::Safe#transaction) is a private
instance helper that wraps a block in a database transaction and issues an
ActiveRecord::Rollback whenever the block's result is a Failure. The
original result is returned either way, so you can keep chaining with
Result#then:
class CreateUserWithAProfile < Micro::Case
def call!
transaction {
call(CreateUser).then(CreateUserProfile)
}
end
end
If the block returns a failure (or raises), every row written inside the
block is rolled back. The helper accepts an optional with: kwarg to pick
the ActiveRecord class on which .transaction is opened — useful for
multi-database Rails apps (ApplicationRecord, AnalyticsRecord,
BillingRecord, …):
class CreateAuditEntry < Micro::Case
def call!
transaction(with: AnalyticsRecord) {
call(WriteAuditLog).then(BumpCounter)
}
end
end
When with: is omitted, the helper falls back to the class macro
(transaction with: …) and then to the global default callback (see below),
which ships as -> { ::ActiveRecord::Base }.
Note: any class passed via
with:(here, on the class macro, or on a flow'stransaction:kwarg) must be a subclass ofActiveRecord::Base. Non-AR classes are rejected withArgumentError. The class-macro validation runs at class-eval time when ActiveRecord is already loaded (typical Rails app); otherwise it's deferred to runtime, so initializer load order doesn't break declarations.Backward compatibility: the pre-5.6.0 positional form
transaction(:activerecord) { ... }still works as an alias fortransaction { ... }. Any other positional value raisesArgumentError— the legacy helper accepted only:activerecord.
transaction with: … — declaring the default for a case
A class macro lets a case declare which ActiveRecord class should own its transactions, so neither the inline helper nor any flow that wraps the case needs to spell it out at every call site. The declaration is inherited by subclasses:
class ApplicationUseCase < Micro::Case
transaction with: ApplicationRecord
end
class CreateUserWithAProfile < ApplicationUseCase
flow(transaction: true, steps: [CreateUser, CreateUserProfile])
# transaction: true resolves to ApplicationRecord because that's
# what the host class declared via `transaction with:`.
end
class BillingCase < ApplicationUseCase
transaction with: BillingRecord
# overrides the inherited declaration for this branch of the tree
end
Micro::Cases.flow(transaction: …, steps: [...]) — flow-level transactions
Pass transaction: together with steps: to wrap an entire flow in a
single transaction. If any step returns a failure (or raises, in a
safe_flow), every database write performed during the flow is rolled back.
The kwarg accepts three forms:
# Use the class-level macro (if the host case declared one) or the
# global default (`ActiveRecord::Base` unless configured otherwise).
Micro::Cases.flow(transaction: true, steps: [CreateUser, CreateUserProfile])
# Pick an explicit ActiveRecord class for this flow only — same `with:`
# vocabulary as the inline helper and the class macro.
Micro::Cases.flow(transaction: { with: AnalyticsRecord }, steps: [
WriteAuditLog,
BumpCounter
])
# safe_flow rolls back on failures AND on unexpected exceptions
Micro::Cases.safe_flow(transaction: { with: ApplicationRecord }, steps: [
CreateUser,
CreateUserProfile
])
# Class-level form
class CreateUserWithAProfile < Micro::Case
flow(transaction: true, steps: [CreateUser, CreateUserProfile])
end
To nest a transactional flow inside another flow, wrap it in a use case
class — Micro::Cases.flow([...]) flattens Flow instances passed as
steps, but does not flatten classes:
class CreateUserAndProfile < Micro::Case
flow(transaction: true, steps: [CreateUser, CreateUserProfile])
end
SignUpFlow = Micro::Cases.flow([
NormalizeParams,
ValidatePassword,
CreateUserAndProfile,
EnqueueIndexingJob
])
If transaction: true is used while ActiveRecord::Base is not loaded the
flow raises Micro::Cases::Error::TransactionAdapterMissing on the first
call so the misconfiguration surfaces immediately. Passing transaction: {
with: SomeClass } skips this check — SomeClass is trusted to respond
to .transaction.
config.default_transaction_class { … } — global default
For Rails apps that use a single abstract record (ApplicationRecord),
configure it once in an initializer instead of declaring it on every case
or flow:
# config/initializers/u_case.rb
Micro::Case.config do |config|
config.default_transaction_class { ApplicationRecord }
end
The callback (block or lambda) is invoked every time a transaction
opens — no memoization — so it's safe to make the return value depend on
runtime state (per-tenant routing, etc.). The default is
-> { ::ActiveRecord::Base }. Resolution order, when a transaction opens:
- Call-site override.
transaction: { with: X }on a flow kwarg, ortransaction(with: X) { ... }on the inline helper. - Host case's
transaction with: Xmacro (walks ancestors). Micro::Case.config.default_transaction_class.call— the global callback (defaults toActiveRecord::Base).
A non-callable assignment to default_transaction_class= raises
ArgumentError at config time so typos like config.default_transaction_class
= 'ApplicationRecord' fail loudly instead of crashing the first transaction.
Internal-step flows under transactions
Internal steps
(the Result#then(:symbol) / | form built inline inside a single
call!) are u-case's third way of composing a flow — an internal
flow. By default an internal flow has no transactional rollback:
side-effects from earlier .then(:method) links persist even when a
later link returns Failure.
There are two natural ways to give an internal flow transactional rollback. Both reuse the helpers already covered above:
1. Wrap the host case in a transaction: true flow. This is the
recommended way once the host case is composed with the rest of the
pipeline. The transaction spans the whole flow call, so a Failure
anywhere — including from any internal .then(:method) link — rolls
back every database write performed during that call:
class CreateUserWithProfileInline < Micro::Case
attributes :name, :info
def call!
create_user
.then(:create_profile)
end
private
def create_user
user = User.create(name: name)
Success result: { user: user }
end
def create_profile(user:, **)
profile = UserProfile.create(user_id: user.id, info: info)
return Failure(:invalid_profile) if profile.errors.any?
Success result: { user: user, profile: profile }
end
end
SignUp = Micro::Cases.flow(transaction: true, steps: [
NormalizeParams,
CreateUserWithProfileInline, # ← internal failure now rolls back
EnqueueIndexingJob
])
# Or class-level:
class SignUp < Micro::Case
flow(transaction: true, steps: [
NormalizeParams,
CreateUserWithProfileInline,
EnqueueIndexingJob
])
end
If create_profile (the internal .then(:create_profile) link)
returns Failure(:invalid_profile), the User row inserted earlier
by create_user is rolled back as part of the same
ActiveRecord::Base.transaction. The result still surfaces the
failure type and the partial transitions, but no row is left behind.
2. Use the inline Micro::Case#transaction helper to scope the
rollback to a single call! without involving an outer flow:
class CreateUserWithProfileInline < Micro::Case
def call!
transaction {
create_user
.then(:create_profile)
}
end
end
This is appropriate when the host case is invoked on its own (not
inside a flow) and you still want the internal flow to be atomic. The
transaction block returns the chain's Result as-is, so you can
keep composing with Result#then after it.
The two approaches compose. If you put CreateUserWithProfileInline
(already using inline transaction { ... }) inside an outer
transaction: true flow, ActiveRecord joins the inner transaction
into the outer one by default — an outer failure rolls back the
inner's writes too. See the Behavior notes below for the full
nesting / flatten rules.
Behavior notes
- Result is unaffected.
transaction: trueonly affects database side-effects.result.data,result.type,result.transitionsandresult.accessible_attributesare identical to those of an equivalent non-transactional flow. Flowinstances get flattened.Micro::Cases.flow([inner_flow, Other])flattensinner_flowinto its leaf steps, which means a transactionalFlowinstance passed this way loses its transaction. Wrap reusable transactional flows in a use case class (the snippet above) to preserve their transaction when nested.- Nested transactions join the outer one. When a transactional flow
is nested inside another transactional flow, ActiveRecord joins them
by default (no
requires_new: true). A failure anywhere in the chain rolls back everything written inside the outermost transaction — including writes performed by the inner flow. - A non-transactional outer commits the inner. If the outer flow is not transactional and the inner transactional flow succeeds, the inner's writes are committed at the end of the inner step. A failure in a later (non-transactional) step does not undo those writes.
- Plain
Micro::Cases.flow(transaction: true, ...)re-raises exceptions. The transaction still rolls back, but the caller has to rescue. UseMicro::Cases.safe_flow(transaction: true, ...)(or the class-level form withMicro::Case::Safe) to capture the exception as a:exceptionfailure result.
Micro::Case::Strict - What is a strict use case?
Answer: it is a kind of use case that will require all the keywords (attributes) on its initialization.
class Double < Micro::Case::Strict
attribute :numbers
def call!
Success result: { numbers: numbers.map { |number| number * 2 } }
end
end
Double.call({})
# The output will be:
# ArgumentError (missing keyword: :numbers)
Micro::Case::Safe - Is there some feature to auto handle exceptions inside of a use case or flow?
Yes, there is one! Like Micro::Case::Strict the Micro::Case::Safe is another kind of use case. It has the ability to auto intercept any exception as a failure result. e.g:
require 'logger'
AppLogger = Logger.new(STDOUT)
class Divide < Micro::Case::Safe
attributes :a, :b
def call!
if a.is_a?(Integer) && b.is_a?(Integer)
Success result: { number: a / b}
else
Failure(:not_an_integer)
end
end
end
result = Divide.call(a: 2, b: 0)
result.type == :exception # true
result.data # { exception: #<ZeroDivisionError...> }
result[:exception].is_a?(ZeroDivisionError) # true
result.on_failure(:exception) do |result|
AppLogger.error(result[:exception].) # E, [2019-08-21T00:05:44.195506 #9532] ERROR -- : divided by 0
end
If you need to handle a specific error, I recommend the usage of a case statement. e,g:
result.on_failure(:exception) do |data, use_case|
case exception = data[:exception]
when ZeroDivisionError then AppLogger.error(exception.)
else AppLogger.debug("#{use_case.class.name} was the use case responsible for the exception")
end
end
Note: It is possible to rescue an exception even when is a safe use case. Examples: https://github.com/serradura/u-case/blob/714c6b658fc6aa02617e6833ddee09eddc760f2a/test/micro/case/safe_test.rb#L90-L118
Micro::Cases::Safe::Flow
As the safe use cases, safe flows can intercept an exception in any of its steps. These are the ways to define one:
module Users
Create = Micro::Cases.safe_flow([
ProcessParams,
ValidateParams,
Persist,
SendToCRM
])
end
Defining within classes:
module Users
class Create < Micro::Case::Safe
flow ProcessParams,
ValidateParams,
Persist,
SendToCRM
end
end
Micro::Case::Result#on_exception
In functional programming errors/exceptions are handled as regular data, the idea is to transform the output even when it happens an unexpected behavior. For many, exceptions are very similar to the GOTO statement, jumping the application flow to paths which could be difficult to figure out how things work in a system.
To address this the Micro::Case::Result has a special hook #on_exception to helping you to handle the control flow in the case of exceptions.
Note: this feature will work better if you use it with a
Micro::Case::Safeflow or use case.
How does it work?
class Divide < Micro::Case::Safe
attributes :a, :b
def call!
Success result: { division: a / b }
end
end
Divide
.call(a: 2, b: 0)
.on_success { |result| puts result[:division] }
.on_exception(TypeError) { puts 'Please, use only numeric attributes.' }
.on_exception(ZeroDivisionError) { |_error| puts "Can't divide a number by 0." }
.on_exception { |_error, _use_case| puts 'Oh no, something went wrong!' }
# Output:
# -------
# Can't divide a number by 0
# Oh no, something went wrong!
Divide
.call(a: 2, b: '2')
.on_success { |result| puts result[:division] }
.on_exception(TypeError) { puts 'Please, use only numeric attributes.' }
.on_exception(ZeroDivisionError) { |_error| puts "Can't divide a number by 0." }
.on_exception { |_error, _use_case| puts 'Oh no, something went wrong!' }
# Output:
# -------
# Please, use only numeric attributes.
# Oh no, something went wrong!
As you can see, this hook has the same behavior of result.on_failure(:exception), but, the idea here is to have a better communication in the code, making an explicit reference when some failure happened because of an exception.
Opting out of the safe mechanism
The "safe" mechanism is opinionated: it converts any unhandled exception inside a use case (or any step of a flow) into a failure result with type: :exception. That is powerful, but it can also produce a fragmented codebase, where some exceptions are handled with rescue inside call! and others are handled later via on_exception / on_failure(:exception) — making the control flow hard to reason about.
If you prefer a single, explicit convention for exception handling — namely, plain rescue statements inside your use cases — you can disable the safe APIs entirely:
Micro::Case.config do |config|
config.disable_safe_features = true
end
Once enabled, the following will raise Micro::Case::Error::SafeFeaturesDisabled, ensuring no one in the codebase can reintroduce the safe path by accident:
- Subclassing
Micro::Case::Safe - Calling
Micro::Cases.safe_flow(...) - Calling
Micro::Case::Result#on_exception
See Micro::Case.config for the full list of available toggles.
Validating attributes with accept: / reject:
Since u-case 5.2.0, every use case includes the accept extension from u-attributes (requires u-attributes >= 2.8). You can declare type expectations (or any other check) directly on the attribute, and the use case will fail automatically with the :invalid_attributes type when any attribute is rejected — no need to validate inside call!.
class CreateUser < Micro::Case
attribute :name, accept: String
attribute :email, accept: ->(value) { value.is_a?(String) && value.include?('@') }
attribute :age, accept: Integer, allow_nil: true
def call!
Success result: { user: User.create!(attributes) }
end
end
CreateUser.call(name: 'Bob', email: 'bob@example.com')
# => #<Success type=:ok ...>
CreateUser.call(name: 42, email: 'not-an-email')
# => #<Failure type=:invalid_attributes data={
# errors: {
# "name" => "expected to be a kind of String",
# "email" => "is invalid"
# }
# }>
The failure type follows the same setting used by the ActiveModel validation integration — see Micro::Case.config and set_activemodel_validation_errors_failure.
When combined with u-case/with_activemodel_validation, the execution order is:
u-attributesresolves the default value of each attribute.u-attributesruns theaccept:/reject:checks.u-caseruns theActiveModelvalidations only if every attribute was accepted.
u-case/with_activemodel_validation - How to validate the use case attributes?
Requirement:
To do this your application must have the activemodel >= 3.2, < 6.1.0 as a dependency.
By default, if your application has ActiveModel as a dependency, any kind of use case can make use of it to validate its attributes.
class Multiply < Micro::Case
attributes :a, :b
validates :a, :b, presence: true, numericality: true
def call!
return Failure :invalid_attributes, result: { errors: self.errors } if invalid?
Success result: { number: a * b }
end
end
But if do you want an automatic way to fail your use cases on validation errors, you could do:
- require 'u-case/with_activemodel_validation' in the Gemfile
gem 'u-case', require: 'u-case/with_activemodel_validation'
- Use the
Micro::Case.configto enable it. Link to this section.
Using this approach, you can rewrite the previous example with less code. e.g:
require 'u-case/with_activemodel_validation'
class Multiply < Micro::Case
attributes :a, :b
validates :a, :b, presence: true, numericality: true
def call!
Success result: { number: a * b }
end
end
Note: After requiring the validation mode, the
Micro::Case::StrictandMicro::Case::Safeclasses will inherit this new behavior.
If I enabled the auto validation, is it possible to disable it only in specific use cases?
Answer: Yes, it is possible. To do this, you will need to use the disable_auto_validation macro. e.g:
require 'u-case/with_activemodel_validation'
class Multiply < Micro::Case
disable_auto_validation
attribute :a
attribute :b
validates :a, :b, presence: true, numericality: true
def call!
Success result: { number: a * b }
end
end
Multiply.call(a: 2, b: 'a')
# The output will be:
# TypeError (String can't be coerced into Integer)
Kind::Validator
The kind gem has a module to enable the validation of data type through ActiveModel validations. So, when you require the 'u-case/with_activemodel_validation', this module will also require the Kind::Validator.
The example below shows how to validate the attributes types.
class Todo::List::AddItem < Micro::Case
attributes :user, :params
validates :user, kind: User
validates :params, kind: ActionController::Parameters
def call!
todo_params = params.require(:todo).permit(:title, :due_at)
todo = user.todos.create(todo_params)
Success result: { todo: todo }
rescue ActionController::ParameterMissing => e
Failure :parameter_missing, result: { message: e. }
end
end
Micro::Case.config
The idea of this resource is to allow the configuration of some u-case features/modules.
I recommend you use it only once in your codebase. e.g. In a Rails initializer.
You can see below, which are the available configurations with their default values:
Micro::Case.config do |config|
# Use ActiveModel to auto-validate your use cases' attributes.
config.enable_activemodel_validation = false
# Use to enable/disable the `Micro::Case::Results#transitions`.
config.enable_transitions = true
# Use to forbid the "safe" features and ensure a single way to handle exceptions
# (via standard `rescue` statements). When set to `true`, the following will raise
# `Micro::Case::Error::SafeFeaturesDisabled`:
# - Subclassing `Micro::Case::Safe`
# - Calling `Micro::Cases.safe_flow(...)`
# - Calling `Micro::Case::Result#on_exception`
config.disable_safe_features = false
# Use to skip the gem's internal argument/contract checks (e.g., "is this a
# Micro::Case?", "is the result type a Symbol?", "is the use case a kind of
# Micro::Case?"). Set to `true` in production for a small performance boost
# once your code paths are exercised by your test suite. The trade-off is that
# incorrect usage will surface as confusing downstream errors instead of the
# gem's curated ones (e.g. `Micro::Case::Error::InvalidUseCase`).
config.disable_runtime_checks = false
end
All checks are consolidated in Micro::Case::Check::Enabled (the default).
Toggling disable_runtime_checks = true swaps Micro::Case.check to
Micro::Case::Check::Disabled — a module with the same signature whose
methods are no-ops — so the validations themselves are not run on each call.
Benchmarks
Micro::Case
Success results
| Gem / Abstraction | Iterations per second | Comparison |
|---|---|---|
| Dry::Monads | 315635.1 | The Fastest |
| Micro::Case | 75837.7 | 4.16x slower |
| Interactor | 59745.5 | 5.28x slower |
| Trailblazer::Operation | 28423.9 | 11.10x slower |
| Dry::Transaction | 10130.9 | 31.16x slower |
Show the full benchmark/ips results.
```ruby # Warming up -------------------------------------- # Interactor 5.711k i/100ms # Trailblazer::Operation # 2.283k i/100ms # Dry::Monads 31.130k i/100ms # Dry::Transaction 994.000 i/100ms # Micro::Case 7.911k i/100ms # Micro::Case::Safe 7.911k i/100ms # Micro::Case::Strict 6.248k i/100ms # Calculating ------------------------------------- # Interactor 59.746k (±29.9%) i/s - 274.128k in 5.049901s # Trailblazer::Operation # 28.424k (±15.8%) i/s - 141.546k in 5.087882s # Dry::Monads 315.635k (± 6.1%) i/s - 1.588M in 5.048914s # Dry::Transaction 10.131k (± 6.4%) i/s - 50.694k in 5.025150s # Micro::Case 75.838k (± 9.7%) i/s - 379.728k in 5.052573s # Micro::Case::Safe 75.461k (±10.1%) i/s - 379.728k in 5.079238s # Micro::Case::Strict 64.235k (± 9.0%) i/s - 324.896k in 5.097028s # Comparison: # Dry::Monads: 315635.1 i/s # Micro::Case: 75837.7 i/s - 4.16x (± 0.00) slower # Micro::Case::Safe: 75461.3 i/s - 4.18x (± 0.00) slower # Micro::Case::Strict: 64234.9 i/s - 4.91x (± 0.00) slower # Interactor: 59745.5 i/s - 5.28x (± 0.00) slower # Trailblazer::Operation: 28423.9 i/s - 11.10x (± 0.00) slower # Dry::Transaction: 10130.9 i/s - 31.16x (± 0.00) slower ```https://github.com/serradura/u-case/blob/main/benchmarks/perfomance/use_case/success_results.rb
Failure results
| Gem / Abstraction | Iterations per second | Comparison |
|---|---|---|
| Dry::Monads | 135386.9 | The Fastest |
| Micro::Case | 73489.3 | 1.85x slower |
| Trailblazer::Operation | 29016.4 | 4.67x slower |
| Interactor | 27037.0 | 5.01x slower |
| Dry::Transaction | 8988.6 | 15.06x slower |
Show the full benchmark/ips results.
```ruby # Warming up -------------------------------------- # Interactor 2.626k i/100ms # Trailblazer::Operation 2.343k i/100ms # Dry::Monads 13.386k i/100ms # Dry::Transaction 868.000 i/100ms # Micro::Case 7.603k i/100ms # Micro::Case::Safe 7.598k i/100ms # Micro::Case::Strict 6.178k i/100ms # Calculating ------------------------------------- # Interactor 27.037k (±24.9%) i/s - 128.674k in 5.102133s # Trailblazer::Operation 29.016k (±12.4%) i/s - 145.266k in 5.074991s # Dry::Monads 135.387k (±15.1%) i/s - 669.300k in 5.055356s # Dry::Transaction 8.989k (± 9.2%) i/s - 45.136k in 5.084820s # Micro::Case 73.247k (± 9.9%) i/s - 364.944k in 5.030449s # Micro::Case::Safe 73.489k (± 9.6%) i/s - 364.704k in 5.007282s # Micro::Case::Strict 61.980k (± 8.0%) i/s - 308.900k in 5.014821s # Comparison: # Dry::Monads: 135386.9 i/s # Micro::Case::Safe: 73489.3 i/s - 1.84x (± 0.00) slower # Micro::Case: 73246.6 i/s - 1.85x (± 0.00) slower # Micro::Case::Strict: 61979.7 i/s - 2.18x (± 0.00) slower # Trailblazer::Operation: 29016.4 i/s - 4.67x (± 0.00) slower # Interactor: 27037.0 i/s - 5.01x (± 0.00) slower # Dry::Transaction: 8988.6 i/s - 15.06x (± 0.00) slower ```https://github.com/serradura/u-case/blob/main/benchmarks/perfomance/use_case/failure_results.rb
Micro::Cases::Flow
| Gems / Abstraction | Success results | Failure results |
|---|---|---|
Micro::Case::Result pipe method |
80936.2 i/s | 78280.4 i/s |
Micro::Case::Result then method |
0x slower | 0x slower |
| Micro::Cases.flow | 0x slower | 0x slower |
| Micro::Case class with an inner flow | 1.72x slower | 1.68x slower |
| Micro::Case class including itself as a step | 1.93x slower | 1.87x slower |
| Interactor::Organizer | 3.33x slower | 3.22x slower |
* The Dry::Monads, Dry::Transaction, Trailblazer::Operation gems are out of this analysis because all of them doesn't have this kind of feature.
Success results - Show the full benchmark/ips results.
```ruby # Warming up -------------------------------------- # Interactor::Organizer 1.809k i/100ms # Micro::Cases.flow([]) 7.808k i/100ms # Micro::Case flow in a class 4.816k i/100ms # Micro::Case including the class 4.094k i/100ms # Micro::Case::Result#| 7.656k i/100ms # Micro::Case::Result#then 7.138k i/100ms # Calculating ------------------------------------- # Interactor::Organizer 24.290k (±24.0%) i/s - 113.967k in 5.032825s # Micro::Cases.flow([]) 74.790k (±11.1%) i/s - 374.784k in 5.071740s # Micro::Case flow in a class 47.043k (± 8.0%) i/s - 235.984k in 5.047477s # Micro::Case including the class 42.030k (± 8.5%) i/s - 208.794k in 5.002138s # Micro::Case::Result#| 80.936k (±15.9%) i/s - 398.112k in 5.052531s # Micro::Case::Result#then 71.459k (± 8.8%) i/s - 356.900k in 5.030526s # Comparison: # Micro::Case::Result#|: 80936.2 i/s # Micro::Cases.flow([]): 74790.1 i/s - same-ish: difference falls within error # Micro::Case::Result#then: 71459.5 i/s - same-ish: difference falls within error # Micro::Case flow in a class: 47042.6 i/s - 1.72x (± 0.00) slower # Micro::Case including the class: 42030.2 i/s - 1.93x (± 0.00) slower # Interactor::Organizer: 24290.3 i/s - 3.33x (± 0.00) slower ```Failure results - Show the full benchmark/ips results.
```ruby # Warming up -------------------------------------- # Interactor::Organizer 1.734k i/100ms # Micro::Cases.flow([]) 7.515k i/100ms # Micro::Case flow in a class 4.636k i/100ms # Micro::Case including the class 4.114k i/100ms # Micro::Case::Result#| 7.588k i/100ms # Micro::Case::Result#then 6.681k i/100ms # Calculating ------------------------------------- # Interactor::Organizer 24.280k (±24.5%) i/s - 112.710k in 5.013334s # Micro::Cases.flow([]) 74.999k (± 9.8%) i/s - 375.750k in 5.055777s # Micro::Case flow in a class 46.681k (± 9.3%) i/s - 236.436k in 5.105105s # Micro::Case including the class 41.921k (± 8.9%) i/s - 209.814k in 5.043622s # Micro::Case::Result#| 78.280k (±12.6%) i/s - 386.988k in 5.022146s # Micro::Case::Result#then 68.898k (± 8.8%) i/s - 347.412k in 5.080116s # Comparison: # Micro::Case::Result#|: 78280.4 i/s # Micro::Cases.flow([]): 74999.4 i/s - same-ish: difference falls within error # Micro::Case::Result#then: 68898.4 i/s - same-ish: difference falls within error # Micro::Case flow in a class: 46681.0 i/s - 1.68x (± 0.00) slower # Micro::Case including the class: 41920.8 i/s - 1.87x (± 0.00) slower # Interactor::Organizer: 24280.0 i/s - 3.22x (± 0.00) slower ```https://github.com/serradura/u-case/blob/main/benchmarks/perfomance/flow/
Running the benchmarks
Performance (Benchmarks IPS)
Clone this repo and access its folder, then run the commands below:
Use cases
ruby benchmarks/perfomance/use_case/failure_results.rb
ruby benchmarks/perfomance/use_case/success_results.rb
Flows
ruby benchmarks/perfomance/flow/failure_results.rb
ruby benchmarks/perfomance/flow/success_results.rb
Memory profiling
Use cases
./benchmarks/memory/use_case/success/with_transitions/analyze.sh
./benchmarks/memory/use_case/success/without_transitions/analyze.sh
Flows
./benchmarks/memory/flow/success/with_transitions/analyze.sh
./benchmarks/memory/flow/success/without_transitions/analyze.sh
Comparisons
Check it out implementations of the same use case with different gems/abstractions.
Examples
1️⃣ Users creation
An example of a flow that defines steps to sanitize, validate, and persist its input data. It has all possible approaches to represent use cases using the
u-casegem.Link: https://github.com/serradura/u-case/blob/main/examples/users_creation
2️⃣ Rails App (API)
This project shows different kinds of architecture (one per commit), and in the last one, how to use the
Micro::Casegem to handle the application business logic.Link: https://github.com/serradura/from-fat-controllers-to-use-cases
3️⃣ CLI calculator
Rake tasks to demonstrate how to handle user data, and how to use different failure types to control the program flow.
Link: https://github.com/serradura/u-case/tree/main/examples/calculator
4️⃣ Rescuing exceptions inside of the use cases
Link: https://github.com/serradura/u-case/blob/main/examples/rescuing_exceptions.rb
Development
After checking out the repo, run bin/setup to install dependencies. Then, run ./test.sh to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/serradura/u-case. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
License
The gem is available as open source under the terms of the MIT License.
Code of Conduct
Everyone interacting in the Micro::Case project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.
