Represent use cases in a simple and powerful way while writing modular, expressive and sequentially logical code.
The main project goals are:
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.
Note: Você entende português? 🇧🇷 🇵🇹 Verifique o README traduzido em pt-BR.
Micro::Case
- How to define a use case?Micro::Case::Result
- What is a use case result?Micro::Case::Result#then
method?
Micro::Cases::Flow
- How to compose use cases?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::Flow
Micro::Case::Result#on_exception
u-case/with_activemodel_validation
- How to validate the use case attributes?Kind::Validator
Micro::Case.config
u-case | branch | ruby | activemodel | u-attributes |
---|---|---|---|---|
unreleased | main | >= 2.2.0 | >= 3.2, < 7.0 | >= 2.7, < 3.0 |
4.5.1 | v4.x | >= 2.2.0 | >= 3.2, < 7.0 | >= 2.7, < 3.0 |
3.1.0 | v3.x | >= 2.2.0 | >= 3.2, < 6.1 | ~> 1.1 |
2.6.0 | v2.x | >= 2.2.0 | >= 3.2, < 6.1 | ~> 1.1 |
1.1.0 | v1.x | >= 2.2.0 | >= 3.2, < 6.1 | ~> 1.1 |
Note: The activemodel is an optional dependency, this module can be enabled to validate the use cases' attributes.
kind
gem.
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 validator
when requiring the u-case/with_activemodel_validation
module, or when the Micro::Case.config
was used to enable it.
u-attributes
gem.
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.
Add this line to your application's Gemfile:
gem 'u-case', '~> 4.5.1'
And then execute:
$ bundle
Or install it yourself as:
$ gem install u-case
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_case
returns the use case responsible for it. This feature is handy to handle a flow failure (this topic will be covered ahead).#type
a Symbol which gives meaning for the result, this is useful to declare different types of failures or success.#data
the result data itself.#[]
and #values_at
are shortcuts to access the #data
values.#key?
returns true
if the key is present in #data
.#value?
returns true
if the given value is present in #data
.#slice
returns a new hash that includes only the given keys. If the given keys don't exist, an empty hash is returned.#on_success
or #on_failure
are hook methods that help you to define the application flow.#then
this 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.#transitions
returns an array with all of transformations wich a result has during a flow.Note: for backward compatibility, you could use the
#value
method as an alias of#data
method.
Every result has a type, and these are their default values:
:ok
when success:error
or :exception
when failuresclass 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.
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
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).
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
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_success
hook!
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_success
hook!
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
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
.
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
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]) }
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 |_message, 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
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.
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.
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#then
increments 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.
}
]
Micro::Case::Result#transitions
?Answer: Yes, it is! You can use the Micro::Case.config
to do this. Link to this section.
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
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].message) # 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.message)
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::Safe
flow 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.
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.config
to 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::Strict
andMicro::Case::Safe
classes will inherit this new behavior.
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.message }
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
end
Micro::Case
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 |
https://github.com/serradura/u-case/blob/main/benchmarks/perfomance/use_case/success_results.rb
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 |
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.
https://github.com/serradura/u-case/blob/main/benchmarks/perfomance/flow/
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
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
Check it out implementations of the same use case with different gems/abstractions.
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-case
gem.Link: https://github.com/serradura/u-case/blob/main/examples/users_creation
This project shows different kinds of architecture (one per commit), and in the last one, how to use the
Micro::Case
gem to handle the application business logic.Link: https://github.com/serradura/from-fat-controllers-to-use-cases
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
Link: https://github.com/serradura/u-case/blob/main/examples/rescuing_exceptions.rb
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.
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.
The gem is available as open source under the terms of the MIT License.
Everyone interacting in the Micro::Case project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.