{"id":13411766,"url":"https://github.com/serradura/u-case","last_synced_at":"2025-05-15T15:06:47.196Z","repository":{"id":37678034,"uuid":"200731758","full_name":"serradura/u-case","owner":"serradura","description":"Represent use cases in a simple and powerful way while writing modular, expressive and sequentially logical code.","archived":false,"fork":false,"pushed_at":"2023-11-08T20:14:05.000Z","size":5051,"stargazers_count":533,"open_issues_count":7,"forks_count":32,"subscribers_count":18,"default_branch":"main","last_synced_at":"2025-05-06T12:19:03.846Z","etag":null,"topics":["application-flow","business-logic","command","interactors","no-callbacks","ruby","ruby-gem","service-object","u-attributes","use-case"],"latest_commit_sha":null,"homepage":"https://rubygems.org/gems/u-case","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/serradura.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-08-05T21:31:59.000Z","updated_at":"2025-04-09T23:55:49.000Z","dependencies_parsed_at":"2024-06-02T20:37:03.067Z","dependency_job_id":"e3bc1d12-8d72-4ce7-a3eb-d041d763607d","html_url":"https://github.com/serradura/u-case","commit_stats":{"total_commits":433,"total_committers":14,"mean_commits":"30.928571428571427","dds":"0.11547344110854507","last_synced_commit":"744685d1abb965b47efa6cb446f2f43569cad419"},"previous_names":["serradura/u-service"],"tags_count":54,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serradura%2Fu-case","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serradura%2Fu-case/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serradura%2Fu-case/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/serradura%2Fu-case/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/serradura","download_url":"https://codeload.github.com/serradura/u-case/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254364270,"owners_count":22058878,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["application-flow","business-logic","command","interactors","no-callbacks","ruby","ruby-gem","service-object","u-attributes","use-case"],"created_at":"2024-07-30T20:01:16.706Z","updated_at":"2025-05-15T15:06:46.452Z","avatar_url":"https://github.com/serradura.png","language":"Ruby","funding_links":[],"categories":["Ruby"],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"./assets/ucase_logo_v1.png\" alt=\"u-case - Represent use cases in a simple and powerful way while writing modular, expressive and sequentially logical code.\"\u003e\n\n  \u003cp align=\"center\"\u003e\u003ci\u003eRepresent use cases in a simple and powerful way while writing modular, expressive and sequentially logical code.\u003c/i\u003e\u003c/p\u003e\n  \u003cbr\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://img.shields.io/badge/ruby-\u003e%3D%202.2.0-ruby.svg?colorA=99004d\u0026colorB=cc0066\" alt=\"Ruby\"\u003e\n\n  \u003ca href=\"https://rubygems.org/gems/u-case\"\u003e\n    \u003cimg alt=\"Gem\" src=\"https://img.shields.io/gem/v/u-case.svg?style=flat-square\"\u003e\n  \u003c/a\u003e\n\n  \u003ca href=\"https://github.com/serradura/u-case/actions/workflows/ci.yml\"\u003e\n    \u003cimg alt=\"Build Status\" src=\"https://github.com/serradura/u-case/actions/workflows/ci.yml/badge.svg\"\u003e\n  \u003c/a\u003e\n\n  \u003ca href=\"https://codeclimate.com/github/serradura/u-case/maintainability\"\u003e\n    \u003cimg alt=\"Maintainability\" src=\"https://api.codeclimate.com/v1/badges/5c3c8ad1b0b943f88efd/maintainability\"\u003e\n  \u003c/a\u003e\n\n  \u003ca href=\"https://codeclimate.com/github/serradura/u-case/test_coverage\"\u003e\n    \u003cimg alt=\"Test Coverage\" src=\"https://api.codeclimate.com/v1/badges/5c3c8ad1b0b943f88efd/test_coverage\"\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\nThe main project goals are:\n1. Easy to use and easy to learn (input **\u003e\u003e** process **\u003e\u003e** output).\n2. Promote immutability (transforming data instead of modifying it) and data integrity.\n3. No callbacks (ex: before, after, around) to avoid code indirections that could compromise the state and understanding of application flows.\n4. Solve complex business logic, by allowing the composition of use cases (flow creation).\n5. Be fast and optimized (Check out the [benchmarks](#benchmarks) section).\n\n\u003e **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.\n\n## Documentation \u003c!-- omit in toc --\u003e\n\nVersion   | Documentation\n--------- | -------------\nunreleased| https://github.com/serradura/u-case/blob/main/README.md\n4.5.1     | https://github.com/serradura/u-case/blob/v4.x/README.md\n3.1.0     | https://github.com/serradura/u-case/blob/v3.x/README.md\n2.6.0     | https://github.com/serradura/u-case/blob/v2.x/README.md\n1.1.0     | https://github.com/serradura/u-case/blob/v1.x/README.md\n\n\u003e **Note:** Você entende português? 🇧🇷\u0026nbsp;🇵🇹 Verifique o [README traduzido em pt-BR](https://github.com/serradura/u-case/blob/main/README.pt-BR.md).\n\n## Table of Contents \u003c!-- omit in toc --\u003e\n- [Compatibility](#compatibility)\n- [Dependencies](#dependencies)\n- [Installation](#installation)\n- [Usage](#usage)\n  - [`Micro::Case` - How to define a use case?](#microcase---how-to-define-a-use-case)\n  - [`Micro::Case::Result` - What is a use case result?](#microcaseresult---what-is-a-use-case-result)\n    - [What are the default result types?](#what-are-the-default-result-types)\n    - [How to define custom result types?](#how-to-define-custom-result-types)\n    - [Is it possible to define a custom type without a result data?](#is-it-possible-to-define-a-custom-type-without-a-result-data)\n    - [How to use the result hooks?](#how-to-use-the-result-hooks)\n    - [Why the hook usage without a defined type exposes the result itself?](#why-the-hook-usage-without-a-defined-type-exposes-the-result-itself)\n      - [Using decomposition to access the result data and type](#using-decomposition-to-access-the-result-data-and-type)\n    - [What happens if a result hook was declared multiple times?](#what-happens-if-a-result-hook-was-declared-multiple-times)\n    - [How to use the `Micro::Case::Result#then` method?](#how-to-use-the-microcaseresultthen-method)\n      - [What does happens when a `Micro::Case::Result#then` receives a block?](#what-does-happens-when-a-microcaseresultthen-receives-a-block)\n      - [How to make attributes data injection using this feature?](#how-to-make-attributes-data-injection-using-this-feature)\n  - [`Micro::Cases::Flow` - How to compose use cases?](#microcasesflow---how-to-compose-use-cases)\n    - [Is it possible to compose a flow with other flows?](#is-it-possible-to-compose-a-flow-with-other-flows)\n    - [Is it possible a flow accumulates its input and merges each success result to use as the argument of the next use cases?](#is-it-possible-a-flow-accumulates-its-input-and-merges-each-success-result-to-use-as-the-argument-of-the-next-use-cases)\n    - [How to understand what is happening during a flow execution?](#how-to-understand-what-is-happening-during-a-flow-execution)\n      - [`Micro::Case::Result#transitions` schema](#microcaseresulttransitions-schema)\n      - [Is it possible disable the `Micro::Case::Result#transitions`?](#is-it-possible-disable-the-microcaseresulttransitions)\n    - [Is it possible to declare a flow that includes the use case itself as a step?](#is-it-possible-to-declare-a-flow-that-includes-the-use-case-itself-as-a-step)\n  - [`Micro::Case::Strict` - What is a strict use case?](#microcasestrict---what-is-a-strict-use-case)\n  - [`Micro::Case::Safe` - Is there some feature to auto handle exceptions inside of a use case or flow?](#microcasesafe---is-there-some-feature-to-auto-handle-exceptions-inside-of-a-use-case-or-flow)\n    - [`Micro::Cases::Safe::Flow`](#microcasessafeflow)\n    - [`Micro::Case::Result#on_exception`](#microcaseresulton_exception)\n  - [`u-case/with_activemodel_validation` - How to validate the use case attributes?](#u-casewith_activemodel_validation---how-to-validate-the-use-case-attributes)\n    - [If I enabled the auto validation, is it possible to disable it only in specific use cases?](#if-i-enabled-the-auto-validation-is-it-possible-to-disable-it-only-in-specific-use-cases)\n    - [`Kind::Validator`](#kindvalidator)\n- [`Micro::Case.config`](#microcaseconfig)\n- [Benchmarks](#benchmarks)\n  - [`Micro::Case`](#microcase)\n    - [Success results](#success-results)\n    - [Failure results](#failure-results)\n  - [`Micro::Cases::Flow`](#microcasesflow)\n  - [Running the benchmarks](#running-the-benchmarks)\n    - [Performance (Benchmarks IPS)](#performance-benchmarks-ips)\n    - [Memory profiling](#memory-profiling)\n  - [Comparisons](#comparisons)\n- [Examples](#examples)\n  - [1️⃣ Users creation](#1️⃣-users-creation)\n  - [2️⃣ Rails App (API)](#2️⃣-rails-app-api)\n  - [3️⃣ CLI calculator](#3️⃣-cli-calculator)\n  - [4️⃣ Rescuing exceptions inside of the use cases](#4️⃣-rescuing-exceptions-inside-of-the-use-cases)\n- [Development](#development)\n- [Contributing](#contributing)\n- [License](#license)\n- [Code of Conduct](#code-of-conduct)\n\n## Compatibility\n\n| u-case         | branch  | ruby     | activemodel   | u-attributes  |\n| -------------- | ------- | -------- | ------------- | ------------- |\n| unreleased     | main    | \u003e= 2.2.0 | \u003e= 3.2, \u003c 7.0 | \u003e= 2.7, \u003c 3.0 |\n| 4.5.1          | v4.x    | \u003e= 2.2.0 | \u003e= 3.2, \u003c 7.0 | \u003e= 2.7, \u003c 3.0 |\n| 3.1.0          | v3.x    | \u003e= 2.2.0 | \u003e= 3.2, \u003c 6.1 |        ~\u003e 1.1 |\n| 2.6.0          | v2.x    | \u003e= 2.2.0 | \u003e= 3.2, \u003c 6.1 |        ~\u003e 1.1 |\n| 1.1.0          | v1.x    | \u003e= 2.2.0 | \u003e= 3.2, \u003c 6.1 |        ~\u003e 1.1 |\n\n\u003e Note: The activemodel is an optional dependency, this module [can be enabled](#u-casewith_activemodel_validation---how-to-validate-use-case-attributes) to validate the use cases' attributes.\n\n## Dependencies\n\n1. [`kind`](https://github.com/serradura/kind) gem.\n\n    A simple type system (at runtime) for Ruby.\n\n    It is used to validate some internal u-case's methods input. This gem also exposes an  [`ActiveModel validator`](https://github.com/serradura/kind#kindvalidator-activemodelvalidations) when requiring the [`u-case/with_activemodel_validation`](#u-casewith_activemodel_validation---how-to-validate-use-case-attributes) module, or when the [`Micro::Case.config`](#microcaseconfig) was used to enable it.\n2. [`u-attributes`](https://github.com/serradura/u-attributes) gem.\n\n    This gem allows defining read-only attributes, that is, your objects will have only getters to access their attributes data.\n    It is used to define the use case attributes.\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'u-case', '~\u003e 4.5.1'\n```\n\nAnd then execute:\n\n    $ bundle\n\nOr install it yourself as:\n\n    $ gem install u-case\n\n## Usage\n\n### `Micro::Case` - How to define a use case?\n\n```ruby\nclass Multiply \u003c Micro::Case\n  # 1. Define its input as attributes\n  attributes :a, :b\n\n  # 2. Define the method `call!` with its business logic\n  def call!\n\n    # 3. Wrap the use case output using the `Success(result: *)` or `Failure(result: *)` methods\n    if a.is_a?(Numeric) \u0026\u0026 b.is_a?(Numeric)\n      Success result: { number: a * b }\n    else\n      Failure result: { message: '`a` and `b` attributes must be numeric' }\n    end\n  end\nend\n\n#========================#\n# Performing an use case #\n#========================#\n\n# Success result\n\nresult = Multiply.call(a: 2, b: 2)\n\nresult.success? # true\nresult.data     # { number: 4 }\n\n# Failure result\n\nbad_result = Multiply.call(a: 2, b: '2')\n\nbad_result.failure? # true\nbad_result.data     # { message: \"`a` and `b` attributes must be numeric\" }\n\n# Note:\n# ----\n# The result of a Micro::Case.call is an instance of Micro::Case::Result\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n### `Micro::Case::Result` - What is a use case result?\n\nA `Micro::Case::Result` stores the use cases output data. These are their main methods:\n- `#success?` returns true if is a successful result.\n- `#failure?` returns true if is an unsuccessful result.\n- `#use_case` returns the use case responsible for it. This feature is handy to handle a flow failure (this topic will be covered ahead).\n- `#type` a Symbol which gives meaning for the result, this is useful to declare different types of failures or success.\n- `#data` the result data itself.\n- `#[]` and `#values_at` are shortcuts to access the `#data` values.\n- `#key?` returns `true` if the key is present in `#data`.\n- `#value?` returns `true` if the given value is present in `#data`.\n- `#slice` returns a new hash that includes only the given keys. If the given keys don't exist, an empty hash is returned.\n- `#on_success` or `#on_failure` are hook methods that help you to define the application flow.\n- `#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.\n- `#transitions` returns an array with all of transformations wich a result [has during a flow](#how-to-understand-what-is-happening-during-a-flow-execution).\n\n\u003e **Note:** for backward compatibility, you could use the `#value` method as an alias of `#data` method.\n\n[⬆️ Back to Top](#table-of-contents-)\n\n#### What are the default result types?\n\nEvery result has a type, and these are their default values:\n- `:ok` when success\n- `:error` or `:exception` when failures\n\n```ruby\nclass Divide \u003c Micro::Case\n  attributes :a, :b\n\n  def call!\n    if invalid_attributes.empty?\n      Success result: { number: a / b }\n    else\n      Failure result: { invalid_attributes: invalid_attributes }\n    end\n  rescue =\u003e exception\n    Failure result: exception\n  end\n\n  private def invalid_attributes\n    attributes.select { |_key, value| !value.is_a?(Numeric) }\n  end\nend\n\n# Success result\n\nresult = Divide.call(a: 2, b: 2)\n\nresult.type     # :ok\nresult.data     # { number: 1 }\nresult.success? # true\nresult.use_case # #\u003cDivide:0x0000 @__attributes={\"a\"=\u003e2, \"b\"=\u003e2}, @a=2, @b=2, @__result=...\u003e\n\n# Failure result (type == :error)\n\nbad_result = Divide.call(a: 2, b: '2')\n\nbad_result.type     # :error\nbad_result.data     # { invalid_attributes: { \"b\"=\u003e\"2\" } }\nbad_result.failure? # true\nbad_result.use_case # #\u003cDivide:0x0000 @__attributes={\"a\"=\u003e2, \"b\"=\u003e\"2\"}, @a=2, @b=\"2\", @__result=...\u003e\n\n# Failure result (type == :exception)\n\nerr_result = Divide.call(a: 2, b: 0)\n\nerr_result.type     # :exception\nerr_result.data     # { exception: \u003cZeroDivisionError: divided by 0\u003e }\nerr_result.failure? # true\nerr_result.use_case # #\u003cDivide:0x0000 @__attributes={\"a\"=\u003e2, \"b\"=\u003e0}, @a=2, @b=0, @__result=#\u003cMicro::Case::Result:0x0000 @use_case=#\u003cDivide:0x0000 ...\u003e, @type=:exception, @value=#\u003cZeroDivisionError: divided by 0\u003e, @success=false\u003e\n\n# Note:\n# ----\n# Any Exception instance which is wrapped by\n# the Failure(result: *) method will receive `:exception` instead of the `:error` type.\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n#### How to define custom result types?\n\nAnswer: Use a symbol as the argument of `Success()`, `Failure()` methods and declare the `result:` keyword to set the result data.\n\n```ruby\nclass Multiply \u003c Micro::Case\n  attributes :a, :b\n\n  def call!\n    if a.is_a?(Numeric) \u0026\u0026 b.is_a?(Numeric)\n      Success result: { number: a * b }\n    else\n      Failure :invalid_data, result: {\n        attributes: attributes.reject { |_, input| input.is_a?(Numeric) }\n      }\n    end\n  end\nend\n\n# Success result\n\nresult = Multiply.call(a: 3, b: 2)\n\nresult.type     # :ok\nresult.data     # { number: 6 }\nresult.success? # true\n\n# Failure result\n\nbad_result = Multiply.call(a: 3, b: '2')\n\nbad_result.type     # :invalid_data\nbad_result.data     # { attributes: {\"b\"=\u003e\"2\"} }\nbad_result.failure? # true\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n#### Is it possible to define a custom type without a result data?\n\nAnswer: 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.\n\n```ruby\nclass Multiply \u003c Micro::Case\n  attributes :a, :b\n\n  def call!\n    if a.is_a?(Numeric) \u0026\u0026 b.is_a?(Numeric)\n      Success result: { number: a * b }\n    else\n      Failure(:invalid_data)\n    end\n  end\nend\n\nresult = Multiply.call(a: 2, b: '2')\n\nresult.failure?            # true\nresult.data                # { :invalid_data =\u003e true }\nresult.type                # :invalid_data\nresult.use_case.attributes # {\"a\"=\u003e2, \"b\"=\u003e\"2\"}\n\n# Note:\n# ----\n# This feature is handy to handle failures in a flow\n# (this topic will be covered ahead).\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n#### How to use the result hooks?\n\nAs [mentioned earlier](#microcaseresult---what-is-a-use-case-result), the `Micro::Case::Result` has two methods to improve the application flow control. They are: `#on_success`, `on_failure`.\n\nThe examples below show how to use them:\n\n```ruby\nclass Double \u003c Micro::Case\n  attribute :number\n\n  def call!\n    return Failure :invalid, result: { msg: 'number must be a numeric value' } unless number.is_a?(Numeric)\n    return Failure :lte_zero, result: { msg: 'number must be greater than 0' } if number \u003c= 0\n\n    Success result: { number: number * 2 }\n  end\nend\n\n#================================#\n# Printing the output if success #\n#================================#\n\nDouble\n  .call(number: 3)\n  .on_success { |result| p result[:number] }\n  .on_failure(:invalid) { |result| raise TypeError, result[:msg] }\n  .on_failure(:lte_zero) { |result| raise ArgumentError, result[:msg] }\n\n# The output will be:\n#   6\n\n#=============================#\n# Raising an error if failure #\n#=============================#\n\nDouble\n  .call(number: -1)\n  .on_success { |result| p result[:number] }\n  .on_failure { |_result, use_case| puts \"#{use_case.class.name} was the use case responsible for the failure\" }\n  .on_failure(:invalid) { |result| raise TypeError, result[:msg] }\n  .on_failure(:lte_zero) { |result| raise ArgumentError, result[:msg] }\n\n# The outputs will be:\n#\n# 1. It will print the message: Double was the use case responsible for the failure\n# 2. It will raise the exception: ArgumentError (the number must be greater than 0)\n\n# Note:\n# ----\n# The use case responsible for the result will always be accessible as the second hook argument\n```\n\n#### Why the hook usage without a defined type exposes the result itself?\n\nAnswer: To allow you to define how to handle the program flow using some conditional statement like an `if` or `case when`.\n\n```ruby\nclass Double \u003c Micro::Case\n  attribute :number\n\n  def call!\n    return Failure(:invalid) unless number.is_a?(Numeric)\n    return Failure :lte_zero, result: attributes(:number) if number \u003c= 0\n\n    Success result: { number: number * 2 }\n  end\nend\n\nDouble\n  .call(number: -1)\n  .on_failure do |result, use_case|\n    case result.type\n    when :invalid then raise TypeError, \"number must be a numeric value\"\n    when :lte_zero then raise ArgumentError, \"number `#{result[:number]}` must be greater than 0\"\n    else raise NotImplementedError\n    end\n  end\n\n# The output will be an exception:\n#\n# ArgumentError (number `-1` must be greater than 0)\n```\n\n\u003e **Note:** The same that was did in the previous examples could be done with `#on_success` hook!\n\n##### Using decomposition to access the result data and type\n\nThe syntax to decompose an Array can be used in assignments and in method/block arguments.\nIf you doesn't know it, check out the [Ruby doc](https://ruby-doc.org/core-2.2.0/doc/syntax/assignment_rdoc.html#label-Array+Decomposition).\n\n```ruby\n# The object exposed in the hook without a type is a Micro::Case::Result and it can be decomposed. e.g:\n\nDouble\n  .call(number: -2)\n  .on_failure do |(data, type), use_case|\n    case type\n    when :invalid then raise TypeError, 'number must be a numeric value'\n    when :lte_zero then raise ArgumentError, \"number `#{data[:number]}` must be greater than 0\"\n    else raise NotImplementedError\n    end\n  end\n\n# The output will be the exception:\n#\n# ArgumentError (the number `-2` must be greater than 0)\n```\n\n\u003e **Note:** The same that was did in the previous examples could be done with `#on_success` hook!\n\n[⬆️ Back to Top](#table-of-contents-)\n\n#### What happens if a result hook was declared multiple times?\n\nAnswer: The hook always will be triggered if it matches the result type.\n\n```ruby\nclass Double \u003c Micro::Case\n  attributes :number\n\n  def call!\n    if number.is_a?(Numeric)\n      Success :computed, result: { number: number * 2 }\n    else\n      Failure :invalid, result: { msg: 'number must be a numeric value' }\n    end\n  end\nend\n\nresult = Double.call(number: 3)\nresult.data         # { number: 6 }\nresult[:number] * 4 # 24\n\naccum = 0\n\nresult\n  .on_success { |result| accum += result[:number] }\n  .on_success { |result| accum += result[:number] }\n  .on_success(:computed) { |result| accum += result[:number] }\n  .on_success(:computed) { |result| accum += result[:number] }\n\naccum # 24\n\nresult[:number] * 4 == accum # true\n```\n\n#### How to use the `Micro::Case::Result#then` method?\n\nThis 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:\n\n```ruby\nclass ForbidNegativeNumber \u003c Micro::Case\n  attribute :number\n\n  def call!\n    return Success result: attributes if number \u003e= 0\n\n    Failure result: attributes\n  end\nend\n\nclass Add3 \u003c Micro::Case\n  attribute :number\n\n  def call!\n    Success result: { number: number + 3 }\n  end\nend\n\nresult1 =\n  ForbidNegativeNumber\n    .call(number: -1)\n    .then(Add3)\n\nresult1.data    # {'number' =\u003e -1}\nresult1.failure? # true\n\n# ---\n\nresult2 =\n  ForbidNegativeNumber\n    .call(number: 1)\n    .then(Add3)\n\nresult2.data     # {'number' =\u003e 4}\nresult2.success? # true\n```\n\n\u003e **Note:** this method changes the [`Micro::Case::Result#transitions`](#how-to-understand-what-is-happening-during-a-flow-execution).\n\n[⬆️ Back to Top](#table-of-contents-)\n\n##### What does happens when a `Micro::Case::Result#then` receives a block?\n\nIt will yields self (a `Micro::Case::Result` instance) to the block, and will return the output of the block instead of itself. e.g:\n\n```ruby\nclass Add \u003c Micro::Case\n  attributes :a, :b\n\n  def call!\n    if Kind.of?(Numeric, a, b)\n      Success result: { sum: a + b }\n    else\n      Failure(:attributes_arent_numbers)\n    end\n  end\nend\n\n# --\n\nsuccess_result =\n  Add\n    .call(a: 2, b: 2)\n    .then { |result| result.success? ? result[:sum] : 0 }\n\nputs success_result # 4\n\n# --\n\nfailure_result =\n  Add\n    .call(a: 2, b: '2')\n    .then { |result| result.success? ? result[:sum] : 0 }\n\nputs failure_result # 0\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n##### How to make attributes data injection using this feature?\n\nPass a Hash as the second argument of the `Micro::Case::Result#then` method.\n\n```ruby\nTodo::FindAllForUser\n  .call(user: current_user, params: params)\n  .then(Paginate)\n  .then(Serialize::PaginatedRelationAsJson, serializer: Todo::Serializer)\n  .on_success { |result| render_json(200, data: result[:todos]) }\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n### `Micro::Cases::Flow` - How to compose use cases?\n\nWe 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.\n\n```ruby\nmodule Steps\n  class ConvertTextToNumbers \u003c Micro::Case\n    attribute :numbers\n\n    def call!\n      if numbers.all? { |value| String(value) =~ /\\d+/ }\n        Success result: { numbers: numbers.map(\u0026:to_i) }\n      else\n        Failure result: { message: 'numbers must contain only numeric types' }\n      end\n    end\n  end\n\n  class Add2 \u003c Micro::Case::Strict\n    attribute :numbers\n\n    def call!\n      Success result: { numbers: numbers.map { |number| number + 2 } }\n    end\n  end\n\n  class Double \u003c Micro::Case::Strict\n    attribute :numbers\n\n    def call!\n      Success result: { numbers: numbers.map { |number| number * 2 } }\n    end\n  end\n\n  class Square \u003c Micro::Case::Strict\n    attribute :numbers\n\n    def call!\n      Success result: { numbers: numbers.map { |number| number * number } }\n    end\n  end\nend\n\n#-------------------------------------------#\n# Creating a flow using Micro::Cases.flow() #\n#-------------------------------------------#\n\nAdd2ToAllNumbers = Micro::Cases.flow([\n  Steps::ConvertTextToNumbers,\n  Steps::Add2\n])\n\nresult = Add2ToAllNumbers.call(numbers: %w[1 1 2 2 3 4])\n\nresult.success? # true\nresult.data    # {:numbers =\u003e [3, 3, 4, 4, 5, 6]}\n\n#-------------------------------#\n# Creating a flow using classes #\n#-------------------------------#\n\nclass DoubleAllNumbers \u003c Micro::Case\n  flow Steps::ConvertTextToNumbers,\n       Steps::Double\nend\n\nDoubleAllNumbers.\n  call(numbers: %w[1 1 b 2 3 4]).\n  on_failure { |result| puts result[:message] } # \"numbers must contain only numeric types\"\n```\n\nWhen happening a failure, the use case responsible will be accessible in the result.\n\n```ruby\nresult = DoubleAllNumbers.call(numbers: %w[1 1 b 2 3 4])\n\nresult.failure?                                    # true\nresult.use_case.is_a?(Steps::ConvertTextToNumbers) # true\n\nresult.on_failure do |_message, use_case|\n  puts \"#{use_case.class.name} was the use case responsible for the failure\" # Steps::ConvertTextToNumbers was the use case responsible for the failure\nend\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n#### Is it possible to compose a flow with other flows?\n\nAnswer: Yes, it is possible.\n\n```ruby\nmodule Steps\n  class ConvertTextToNumbers \u003c Micro::Case\n    attribute :numbers\n\n    def call!\n      if numbers.all? { |value| String(value) =~ /\\d+/ }\n        Success result: { numbers: numbers.map(\u0026:to_i) }\n      else\n        Failure result: { message: 'numbers must contain only numeric types' }\n      end\n    end\n  end\n\n  class Add2 \u003c Micro::Case::Strict\n    attribute :numbers\n\n    def call!\n      Success result: { numbers: numbers.map { |number| number + 2 } }\n    end\n  end\n\n  class Double \u003c Micro::Case::Strict\n    attribute :numbers\n\n    def call!\n      Success result: { numbers: numbers.map { |number| number * 2 } }\n    end\n  end\n\n  class Square \u003c Micro::Case::Strict\n    attribute :numbers\n\n    def call!\n      Success result: { numbers: numbers.map { |number| number * number } }\n    end\n  end\nend\n\nDoubleAllNumbers =\n  Micro::Cases.flow([Steps::ConvertTextToNumbers, Steps::Double])\n\nSquareAllNumbers =\n  Micro::Cases.flow([Steps::ConvertTextToNumbers, Steps::Square])\n\nDoubleAllNumbersAndAdd2 =\n  Micro::Cases.flow([DoubleAllNumbers, Steps::Add2])\n\nSquareAllNumbersAndAdd2 =\n  Micro::Cases.flow([SquareAllNumbers, Steps::Add2])\n\nSquareAllNumbersAndDouble =\n  Micro::Cases.flow([SquareAllNumbersAndAdd2, DoubleAllNumbers])\n\nDoubleAllNumbersAndSquareAndAdd2 =\n  Micro::Cases.flow([DoubleAllNumbers, SquareAllNumbersAndAdd2])\n\nSquareAllNumbersAndDouble\n  .call(numbers: %w[1 1 2 2 3 4])\n  .on_success { |result| p result[:numbers] } # [6, 6, 12, 12, 22, 36]\n\nDoubleAllNumbersAndSquareAndAdd2\n  .call(numbers: %w[1 1 2 2 3 4])\n  .on_success { |result| p result[:numbers] } # [6, 6, 18, 18, 38, 66]\n```\n\n\u003e **Note:** You can blend any [approach](#microcasesflow---how-to-compose-use-cases) to create use case flows - [examples](https://github.com/serradura/u-case/blob/714c6b658fc6aa02617e6833ddee09eddc760f2a/test/micro/cases/flow/blend_test.rb#L5-L35).\n\n[⬆️ Back to Top](#table-of-contents-)\n\n#### Is it possible a flow accumulates its input and merges each success result to use as the argument of the next use cases?\n\nAnswer: Yes, it is possible! Look at the example below to understand how the data accumulation works inside of a flow execution.\n\n```ruby\nmodule Users\n  class FindByEmail \u003c Micro::Case\n    attribute :email\n\n    def call!\n      user = User.find_by(email: email)\n\n      return Success result: { user: user } if user\n\n      Failure(:user_not_found)\n    end\n  end\nend\n\nmodule Users\n  class ValidatePassword \u003c Micro::Case::Strict\n    attributes :user, :password\n\n    def call!\n      return Failure(:user_must_be_persisted) if user.new_record?\n      return Failure(:wrong_password) if user.wrong_password?(password)\n\n      return Success result: attributes(:user)\n    end\n  end\nend\n\nmodule Users\n  Authenticate = Micro::Cases.flow([\n    FindByEmail,\n    ValidatePassword\n  ])\nend\n\nUsers::Authenticate\n  .call(email: 'somebody@test.com', password: 'password')\n  .on_success { |result| sign_in(result[:user]) }\n  .on_failure(:wrong_password) { render status: 401 }\n  .on_failure(:user_not_found) { render status: 404 }\n```\n\nFirst, let's see the attributes used by each use case:\n\n```ruby\nclass Users::FindByEmail \u003c Micro::Case\n  attribute :email\nend\n\nclass Users::ValidatePassword \u003c Micro::Case\n  attributes :user, :password\nend\n```\n\nAs you can see the `Users::ValidatePassword` expects a user as its input. So, how does it receives the user?\nAnswer: It receives the user from the `Users::FindByEmail` success result!\n\nAnd 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!\n\n\u003e input **\u003e\u003e** process **\u003e\u003e** output\n\n\u003e **Note:** Check out these test examples [Micro::Cases::Flow](https://github.com/serradura/u-case/blob/c96a3650469da40dc9f83ff678204055b7015d01/test/micro/cases/flow/result_transitions_test.rb) and [Micro::Cases::Safe::Flow](https://github.com/serradura/u-case/blob/c96a3650469da40dc9f83ff678204055b7015d01/test/micro/cases/safe/flow/result_transitions_test.rb) to see different use cases having access to the data in a flow.\n\n[⬆️ Back to Top](#table-of-contents-)\n\n#### How to understand what is happening during a flow execution?\n\nUse `Micro::Case::Result#transitions`!\n\nLet's use the [previous section example](#is-it-possible-a-flow-accumulates-its-input-and-merges-each-success-result-to-use-as-the-argument-of-the-next-use-cases) to ilustrate how to use this feature.\n\n```ruby\nuser_authenticated =\n  Users::Authenticate.call(email: 'rodrigo@test.com', password: user_password)\n\nuser_authenticated.transitions\n[\n  {\n    :use_case =\u003e {\n      :class      =\u003e Users::FindByEmail,\n      :attributes =\u003e { :email =\u003e \"rodrigo@test.com\" }\n    },\n    :success =\u003e {\n      :type  =\u003e :ok,\n      :result =\u003e {\n        :user =\u003e #\u003cUser:0x00007fb57b1c5f88 @email=\"rodrigo@test.com\" ...\u003e\n      }\n    },\n    :accessible_attributes =\u003e [ :email, :password ]\n  },\n  {\n    :use_case =\u003e {\n      :class      =\u003e Users::ValidatePassword,\n      :attributes =\u003e {\n        :user     =\u003e #\u003cUser:0x00007fb57b1c5f88 @email=\"rodrigo@test.com\" ...\u003e\n        :password =\u003e \"123456\"\n      }\n    },\n    :success =\u003e {\n      :type  =\u003e :ok,\n      :result =\u003e {\n        :user =\u003e #\u003cUser:0x00007fb57b1c5f88 @email=\"rodrigo@test.com\" ...\u003e\n      }\n    },\n    :accessible_attributes =\u003e [ :email, :password, :user ]\n  }\n]\n```\n\nThe example above shows the output generated by the `Micro::Case::Result#transitions`.\nWith 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.\n\nAnd 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](#is-it-possible-a-flow-accumulates-its-input-and-merges-each-success-result-to-use-as-the-argument-of-the-next-use-cases).\n\n\u003e **Note:** The [`Micro::Case::Result#then`](#how-to-use-the-microcaseresultthen-method) increments the `Micro::Case::Result#transitions`.\n\n##### `Micro::Case::Result#transitions` schema\n```ruby\n[\n  {\n    use_case: {\n      class:      \u003cMicro::Case\u003e,# Use case which was executed\n      attributes: \u003cHash\u003e        # (Input) The use case's attributes\n    },\n    [success:, failure:] =\u003e {   # (Output)\n      type:  \u003cSymbol\u003e,          # Result type. Defaults:\n                                # Success = :ok, Failure = :error/:exception\n      result: \u003cHash\u003e            # The data returned by the use case result\n    },\n    accessible_attributes: \u003cArray\u003e, # Properties that can be accessed by the use case's attributes,\n                                    # it starts with Hash used to invoke it and that will be incremented\n                                    # with the result values of each use case in the flow.\n  }\n]\n```\n\n##### Is it possible disable the `Micro::Case::Result#transitions`?\n\nAnswer: Yes, it is! You can use the `Micro::Case.config` to do this. [Link to](#microcaseconfig) this section.\n\n#### Is it possible to declare a flow that includes the use case itself as a step?\n\nAnswer: Yes, it is! You can use `self` or the `self.call!` macro. e.g:\n\n```ruby\nclass ConvertTextToNumber \u003c Micro::Case\n  attribute :text\n\n  def call!\n    Success result: { number: text.to_i }\n  end\nend\n\nclass ConvertNumberToText \u003c Micro::Case\n  attribute :number\n\n  def call!\n    Success result: { text: number.to_s }\n  end\nend\n\nclass Double \u003c Micro::Case\n  flow ConvertTextToNumber,\n       self.call!,\n       ConvertNumberToText\n\n  attribute :number\n\n  def call!\n    Success result: { number: number * 2 }\n  end\nend\n\nresult = Double.call(text: '4')\n\nresult.success? # true\nresult[:number] # \"8\"\n```\n\n\u003e **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\n\n[⬆️ Back to Top](#table-of-contents-)\n\n### `Micro::Case::Strict` - What is a strict use case?\n\nAnswer: it is a kind of use case that will require all the keywords (attributes) on its initialization.\n\n```ruby\nclass Double \u003c Micro::Case::Strict\n  attribute :numbers\n\n  def call!\n    Success result: { numbers: numbers.map { |number| number * 2 } }\n  end\nend\n\nDouble.call({})\n\n# The output will be:\n# ArgumentError (missing keyword: :numbers)\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n### `Micro::Case::Safe` - Is there some feature to auto handle exceptions inside of a use case or flow?\n\nYes, 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:\n\n```ruby\nrequire 'logger'\n\nAppLogger = Logger.new(STDOUT)\n\nclass Divide \u003c Micro::Case::Safe\n  attributes :a, :b\n\n  def call!\n    if a.is_a?(Integer) \u0026\u0026 b.is_a?(Integer)\n      Success result: { number: a / b}\n    else\n      Failure(:not_an_integer)\n    end\n  end\nend\n\nresult = Divide.call(a: 2, b: 0)\nresult.type == :exception                   # true\nresult.data                                 # { exception: #\u003cZeroDivisionError...\u003e }\nresult[:exception].is_a?(ZeroDivisionError) # true\n\nresult.on_failure(:exception) do |result|\n  AppLogger.error(result[:exception].message) # E, [2019-08-21T00:05:44.195506 #9532] ERROR -- : divided by 0\nend\n```\n\nIf you need to handle a specific error, I recommend the usage of a case statement. e,g:\n\n```ruby\nresult.on_failure(:exception) do |data, use_case|\n  case exception = data[:exception]\n  when ZeroDivisionError then AppLogger.error(exception.message)\n  else AppLogger.debug(\"#{use_case.class.name} was the use case responsible for the exception\")\n  end\nend\n```\n\n\u003e **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\n\n[⬆️ Back to Top](#table-of-contents-)\n\n#### `Micro::Cases::Safe::Flow`\n\nAs the safe use cases, safe flows can intercept an exception in any of its steps. These are the ways to define one:\n\n```ruby\nmodule Users\n  Create = Micro::Cases.safe_flow([\n    ProcessParams,\n    ValidateParams,\n    Persist,\n    SendToCRM\n  ])\nend\n```\n\nDefining within classes:\n\n```ruby\nmodule Users\n  class Create \u003c Micro::Case::Safe\n    flow ProcessParams,\n         ValidateParams,\n         Persist,\n         SendToCRM\n  end\nend\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n#### `Micro::Case::Result#on_exception`\n\nIn 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](https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why), jumping the application flow to paths which could be difficult to figure out how things work in a system.\n\nTo 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.\n\n\u003e **Note**: this feature will work better if you use it with a `Micro::Case::Safe` flow or use case.\n\n**How does it work?**\n\n```ruby\nclass Divide \u003c Micro::Case::Safe\n  attributes :a, :b\n\n  def call!\n    Success result: { division: a / b }\n  end\nend\n\nDivide\n  .call(a: 2, b: 0)\n  .on_success { |result| puts result[:division] }\n  .on_exception(TypeError) { puts 'Please, use only numeric attributes.' }\n  .on_exception(ZeroDivisionError) { |_error| puts \"Can't divide a number by 0.\" }\n  .on_exception { |_error, _use_case| puts 'Oh no, something went wrong!' }\n\n# Output:\n# -------\n# Can't divide a number by 0\n# Oh no, something went wrong!\n\nDivide\n  .call(a: 2, b: '2')\n  .on_success { |result| puts result[:division] }\n  .on_exception(TypeError) { puts 'Please, use only numeric attributes.' }\n  .on_exception(ZeroDivisionError) { |_error| puts \"Can't divide a number by 0.\" }\n  .on_exception { |_error, _use_case| puts 'Oh no, something went wrong!' }\n\n# Output:\n# -------\n# Please, use only numeric attributes.\n# Oh no, something went wrong!\n```\n\nAs 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.\n\n[⬆️ Back to Top](#table-of-contents-)\n\n### `u-case/with_activemodel_validation` - How to validate the use case attributes?\n\n**Requirement:**\n\nTo do this your application must have the [activemodel \u003e= 3.2, \u003c 6.1.0](https://rubygems.org/gems/activemodel) as a dependency.\n\nBy default, if your application has ActiveModel as a dependency, any kind of use case can make use of it to validate its attributes.\n\n```ruby\nclass Multiply \u003c Micro::Case\n  attributes :a, :b\n\n  validates :a, :b, presence: true, numericality: true\n\n  def call!\n    return Failure :invalid_attributes, result: { errors: self.errors } if invalid?\n\n    Success result: { number: a * b }\n  end\nend\n```\n\nBut if do you want an automatic way to fail your use cases on validation errors, you could do:\n\n1. **require 'u-case/with_activemodel_validation'** in the Gemfile\n\n  ```ruby\n  gem 'u-case', require: 'u-case/with_activemodel_validation'\n  ```\n\n2. Use the `Micro::Case.config` to enable it. [Link to](#microcaseconfig) this section.\n\nUsing this approach, you can rewrite the previous example with less code. e.g:\n\n```ruby\nrequire 'u-case/with_activemodel_validation'\n\nclass Multiply \u003c Micro::Case\n  attributes :a, :b\n\n  validates :a, :b, presence: true, numericality: true\n\n  def call!\n    Success result: { number: a * b }\n  end\nend\n```\n\n\u003e **Note:** After requiring the validation mode, the `Micro::Case::Strict` and `Micro::Case::Safe` classes will inherit this new behavior.\n\n#### If I enabled the auto validation, is it possible to disable it only in specific use cases?\n\nAnswer: Yes, it is possible. To do this, you will need to use the `disable_auto_validation` macro. e.g:\n\n```ruby\nrequire 'u-case/with_activemodel_validation'\n\nclass Multiply \u003c Micro::Case\n  disable_auto_validation\n\n  attribute :a\n  attribute :b\n  validates :a, :b, presence: true, numericality: true\n\n  def call!\n    Success result: { number: a * b }\n  end\nend\n\nMultiply.call(a: 2, b: 'a')\n\n# The output will be:\n# TypeError (String can't be coerced into Integer)\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n#### `Kind::Validator`\n\nThe [kind gem](https://github.com/serradura/kind) has a module to enable the validation of data type through [`ActiveModel validations`](https://guides.rubyonrails.org/active_model_basics.html#validations). So, when you require the `'u-case/with_activemodel_validation'`, this module will also require the [`Kind::Validator`](https://github.com/serradura/kind#kindvalidator-activemodelvalidations).\n\nThe example below shows how to validate the attributes types.\n\n```ruby\nclass Todo::List::AddItem \u003c Micro::Case\n  attributes :user, :params\n\n  validates :user, kind: User\n  validates :params, kind: ActionController::Parameters\n\n  def call!\n    todo_params = params.require(:todo).permit(:title, :due_at)\n\n    todo = user.todos.create(todo_params)\n\n    Success result: { todo: todo }\n  rescue ActionController::ParameterMissing =\u003e e\n    Failure :parameter_missing, result: { message: e.message }\n  end\nend\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n## `Micro::Case.config`\n\nThe idea of this resource is to allow the configuration of some `u-case` features/modules.\nI recommend you use it only once in your codebase. e.g. In a Rails initializer.\n\nYou can see below, which are the available configurations with their default values:\n\n```ruby\nMicro::Case.config do |config|\n  # Use ActiveModel to auto-validate your use cases' attributes.\n  config.enable_activemodel_validation = false\n\n  # Use to enable/disable the `Micro::Case::Results#transitions`.\n  config.enable_transitions = true\nend\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n## Benchmarks\n\n### `Micro::Case`\n\n#### Success results\n\n| Gem / Abstraction      | Iterations per second |       Comparison  |\n| -----------------      | --------------------: | ----------------: |\n| Dry::Monads            |              315635.1 | _**The Fastest**_ |\n| **Micro::Case**        |               75837.7 |     4.16x slower  |\n| Interactor             |               59745.5 |     5.28x slower  |\n| Trailblazer::Operation |               28423.9 |    11.10x slower  |\n| Dry::Transaction       |               10130.9 |    31.16x slower  |\n\n\u003cdetails\u003e\n  \u003csummary\u003eShow the full \u003ca href=\"https://github.com/evanphx/benchmark-ips\"\u003ebenchmark/ips\u003c/a\u003e results.\u003c/summary\u003e\n\n```ruby\n# Warming up --------------------------------------\n#           Interactor     5.711k i/100ms\n# Trailblazer::Operation\n#                          2.283k i/100ms\n#          Dry::Monads    31.130k i/100ms\n#     Dry::Transaction   994.000  i/100ms\n#          Micro::Case     7.911k i/100ms\n#    Micro::Case::Safe     7.911k i/100ms\n#  Micro::Case::Strict     6.248k i/100ms\n\n# Calculating -------------------------------------\n#           Interactor     59.746k (±29.9%) i/s -    274.128k in   5.049901s\n# Trailblazer::Operation\n#                          28.424k (±15.8%) i/s -    141.546k in   5.087882s\n#          Dry::Monads    315.635k (± 6.1%) i/s -      1.588M in   5.048914s\n#     Dry::Transaction     10.131k (± 6.4%) i/s -     50.694k in   5.025150s\n#          Micro::Case     75.838k (± 9.7%) i/s -    379.728k in   5.052573s\n#    Micro::Case::Safe     75.461k (±10.1%) i/s -    379.728k in   5.079238s\n#  Micro::Case::Strict     64.235k (± 9.0%) i/s -    324.896k in   5.097028s\n\n# Comparison:\n#          Dry::Monads:   315635.1 i/s\n#          Micro::Case:    75837.7 i/s - 4.16x  (± 0.00) slower\n#    Micro::Case::Safe:    75461.3 i/s - 4.18x  (± 0.00) slower\n#  Micro::Case::Strict:    64234.9 i/s - 4.91x  (± 0.00) slower\n#           Interactor:    59745.5 i/s - 5.28x  (± 0.00) slower\n# Trailblazer::Operation:    28423.9 i/s - 11.10x  (± 0.00) slower\n#     Dry::Transaction:    10130.9 i/s - 31.16x  (± 0.00) slower\n```\n\u003c/details\u003e\n\nhttps://github.com/serradura/u-case/blob/main/benchmarks/perfomance/use_case/success_results.rb\n\n#### Failure results\n\n| Gem / Abstraction      | Iterations per second |       Comparison  |\n| -----------------      | --------------------: | ----------------: |\n| Dry::Monads            |              135386.9 | _**The Fastest**_ |\n| **Micro::Case**        |               73489.3 |     1.85x slower  |\n| Trailblazer::Operation |               29016.4 |     4.67x slower  |\n| Interactor             |               27037.0 |     5.01x slower  |\n| Dry::Transaction       |                8988.6 |    15.06x slower  |\n\n\u003cdetails\u003e\n  \u003csummary\u003eShow the full \u003ca href=\"https://github.com/evanphx/benchmark-ips\"\u003ebenchmark/ips\u003c/a\u003e results.\u003c/summary\u003e\n\n```ruby\n# Warming up --------------------------------------\n#           Interactor     2.626k i/100ms\n# Trailblazer::Operation   2.343k i/100ms\n#          Dry::Monads    13.386k i/100ms\n#     Dry::Transaction   868.000  i/100ms\n#          Micro::Case     7.603k i/100ms\n#    Micro::Case::Safe     7.598k i/100ms\n#  Micro::Case::Strict     6.178k i/100ms\n\n# Calculating -------------------------------------\n#           Interactor     27.037k (±24.9%) i/s -    128.674k in   5.102133s\n# Trailblazer::Operation   29.016k (±12.4%) i/s -    145.266k in   5.074991s\n#          Dry::Monads    135.387k (±15.1%) i/s -    669.300k in   5.055356s\n#     Dry::Transaction      8.989k (± 9.2%) i/s -     45.136k in   5.084820s\n#          Micro::Case     73.247k (± 9.9%) i/s -    364.944k in   5.030449s\n#    Micro::Case::Safe     73.489k (± 9.6%) i/s -    364.704k in   5.007282s\n#  Micro::Case::Strict     61.980k (± 8.0%) i/s -    308.900k in   5.014821s\n\n# Comparison:\n#          Dry::Monads:   135386.9 i/s\n#    Micro::Case::Safe:    73489.3 i/s - 1.84x  (± 0.00) slower\n#          Micro::Case:    73246.6 i/s - 1.85x  (± 0.00) slower\n#  Micro::Case::Strict:    61979.7 i/s - 2.18x  (± 0.00) slower\n# Trailblazer::Operation:    29016.4 i/s - 4.67x  (± 0.00) slower\n#           Interactor:    27037.0 i/s - 5.01x  (± 0.00) slower\n#     Dry::Transaction:     8988.6 i/s - 15.06x  (± 0.00) slower\n```\n\u003c/details\u003e\n\nhttps://github.com/serradura/u-case/blob/main/benchmarks/perfomance/use_case/failure_results.rb\n\n---\n\n### `Micro::Cases::Flow`\n\n| Gems / Abstraction      | [Success results](https://github.com/serradura/u-case/blob/main/benchmarks/perfomance/flow/success_results.rb) | [Failure results](https://github.com/serradura/u-case/blob/main/benchmarks/perfomance/flow/failure_results.rb) |\n| ------------------------------------------- | ----------------: | ----------------: |\n| Micro::Case::Result `pipe` method           |       80936.2 i/s |       78280.4 i/s |\n| Micro::Case::Result `then` method           |         0x slower |         0x slower |\n| Micro::Cases.flow                           |         0x slower |         0x slower |\n| Micro::Case class with an inner flow        |      1.72x slower |      1.68x slower |\n| Micro::Case class including itself as a step|      1.93x slower |      1.87x slower |\n| Interactor::Organizer                       |      3.33x slower |      3.22x slower |\n\n\\* The `Dry::Monads`, `Dry::Transaction`, `Trailblazer::Operation` gems are out of this analysis because all of them doesn't have this kind of feature.\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003cstrong\u003eSuccess results\u003c/strong\u003e - Show the full benchmark/ips results.\u003c/summary\u003e\n\n```ruby\n# Warming up --------------------------------------\n# Interactor::Organizer             1.809k i/100ms\n# Micro::Cases.flow([])             7.808k i/100ms\n# Micro::Case flow in a class       4.816k i/100ms\n# Micro::Case including the class   4.094k i/100ms\n# Micro::Case::Result#|             7.656k i/100ms\n# Micro::Case::Result#then          7.138k i/100ms\n\n# Calculating -------------------------------------\n# Interactor::Organizer             24.290k (±24.0%) i/s -    113.967k in   5.032825s\n# Micro::Cases.flow([])             74.790k (±11.1%) i/s -    374.784k in   5.071740s\n# Micro::Case flow in a class       47.043k (± 8.0%) i/s -    235.984k in   5.047477s\n# Micro::Case including the class   42.030k (± 8.5%) i/s -    208.794k in   5.002138s\n# Micro::Case::Result#|             80.936k (±15.9%) i/s -    398.112k in   5.052531s\n# Micro::Case::Result#then          71.459k (± 8.8%) i/s -    356.900k in   5.030526s\n\n# Comparison:\n# Micro::Case::Result#|:            80936.2 i/s\n# Micro::Cases.flow([]):            74790.1 i/s - same-ish: difference falls within error\n# Micro::Case::Result#then:         71459.5 i/s - same-ish: difference falls within error\n# Micro::Case flow in a class:      47042.6 i/s - 1.72x  (± 0.00) slower\n# Micro::Case including the class:  42030.2 i/s - 1.93x  (± 0.00) slower\n# Interactor::Organizer:            24290.3 i/s - 3.33x  (± 0.00) slower\n```\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003cstrong\u003eFailure results\u003c/strong\u003e - Show the full benchmark/ips results.\u003c/summary\u003e\n\n```ruby\n# Warming up --------------------------------------\n# Interactor::Organizer            1.734k i/100ms\n# Micro::Cases.flow([])            7.515k i/100ms\n# Micro::Case flow in a class      4.636k i/100ms\n# Micro::Case including the class  4.114k i/100ms\n# Micro::Case::Result#|            7.588k i/100ms\n# Micro::Case::Result#then         6.681k i/100ms\n\n# Calculating -------------------------------------\n# Interactor::Organizer            24.280k (±24.5%) i/s -    112.710k in   5.013334s\n# Micro::Cases.flow([])            74.999k (± 9.8%) i/s -    375.750k in   5.055777s\n# Micro::Case flow in a class      46.681k (± 9.3%) i/s -    236.436k in   5.105105s\n# Micro::Case including the class  41.921k (± 8.9%) i/s -    209.814k in   5.043622s\n# Micro::Case::Result#|            78.280k (±12.6%) i/s -    386.988k in   5.022146s\n# Micro::Case::Result#then         68.898k (± 8.8%) i/s -    347.412k in   5.080116s\n\n# Comparison:\n# Micro::Case::Result#|:            78280.4 i/s\n# Micro::Cases.flow([]):            74999.4 i/s - same-ish: difference falls within error\n# Micro::Case::Result#then:         68898.4 i/s - same-ish: difference falls within error\n# Micro::Case flow in a class:      46681.0 i/s - 1.68x  (± 0.00) slower\n# Micro::Case including the class:  41920.8 i/s - 1.87x  (± 0.00) slower\n# Interactor::Organizer:            24280.0 i/s - 3.22x  (± 0.00) slower\n```\n\u003c/details\u003e\n\nhttps://github.com/serradura/u-case/blob/main/benchmarks/perfomance/flow/\n\n[⬆️ Back to Top](#table-of-contents-)\n\n### Running the benchmarks\n\n#### Performance (Benchmarks IPS)\n\nClone this repo and access its folder, then run the commands below:\n\n**Use cases**\n\n```sh\nruby benchmarks/perfomance/use_case/failure_results.rb\nruby benchmarks/perfomance/use_case/success_results.rb\n```\n\n**Flows**\n\n```sh\nruby benchmarks/perfomance/flow/failure_results.rb\nruby benchmarks/perfomance/flow/success_results.rb\n```\n\n#### Memory profiling\n\n**Use cases**\n\n```sh\n./benchmarks/memory/use_case/success/with_transitions/analyze.sh\n./benchmarks/memory/use_case/success/without_transitions/analyze.sh\n```\n\n**Flows**\n\n```sh\n./benchmarks/memory/flow/success/with_transitions/analyze.sh\n./benchmarks/memory/flow/success/without_transitions/analyze.sh\n```\n\n[⬆️ Back to Top](#table-of-contents-)\n\n### Comparisons\n\nCheck it out implementations of the same use case with different gems/abstractions.\n\n* [interactor](https://github.com/serradura/u-case/blob/main/comparisons/interactor.rb)\n* [u-case](https://github.com/serradura/u-case/blob/main/comparisons/u-case.rb)\n\n[⬆️ Back to Top](#table-of-contents-)\n\n## Examples\n\n### 1️⃣ Users creation\n\n\u003e 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.\n\u003e\n\u003e Link: https://github.com/serradura/u-case/blob/main/examples/users_creation\n\n### 2️⃣ Rails App (API)\n\n\u003e 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.\n\u003e\n\u003e Link: https://github.com/serradura/from-fat-controllers-to-use-cases\n\n### 3️⃣ CLI calculator\n\n\u003e Rake tasks to demonstrate how to handle user data, and how to use different failure types to control the program flow.\n\u003e\n\u003e Link: https://github.com/serradura/u-case/tree/main/examples/calculator\n\n### 4️⃣ Rescuing exceptions inside of the use cases\n\n\u003e Link: https://github.com/serradura/u-case/blob/main/examples/rescuing_exceptions.rb\n\n[⬆️ Back to Top](#table-of-contents-)\n\n## Development\n\nAfter 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.\n\nTo 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](https://rubygems.org).\n\n## Contributing\n\nBug 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](http://contributor-covenant.org) code of conduct.\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).\n\n## Code of Conduct\n\nEveryone interacting in the Micro::Case project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/serradura/u-case/blob/main/CODE_OF_CONDUCT.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fserradura%2Fu-case","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fserradura%2Fu-case","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fserradura%2Fu-case/lists"}