Applying the Use Case Pattern with Rails | The Codest

Ask questions Research chat →

https://thecodest.co/blog/applying-the-use-case-pattern-with-rails · scraped

ruby

Scraped Content

— 848 words · 2026-06-11 17:20:02 UTC ·

Excerpt

![](https://prod-files-secure.s3.us-west-2.amazonaws.com/871f1661-80b8-4d0c-ac3b-2adfc6ff4c66/b1cbe17b-022d-47d7-89ad-2f18060e88e2/applying_the_use_case_pattern_with_rails.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=ASIAZI2LB466S7MFUMTW%2F20260611%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20260611T172002Z&X-Amz-Expires=3600&X-Amz-Security-Token=IQoJb3JpZ2luX2VjEDkaCXVzLXdlc3QtMiJIMEYCIQDOz0YR4iHjxIwnyVYYPaqxazHcsVAhzex0Uk80GUhZigIhAMDx3XC1Z3ka%2Brdk9iZsDCXlMCD0UDx94Tzl2fokHxn%2BKv8DCAEQABoMNjM3NDIzMTgzODA1IgxJ61jrLhSzP5tKoIIq3AN6%2FM1JRJXKejJGPe9IQPq4s9w8UGg%2FqwH8UmIvAKuxrnryZr9L4Cpv%2B1TBK2K%2BTh6Dg5kDH95bbfVSlwSI3QNR4V5FQMh0bX%2B0wxBCr2VxiR6e6P2NAL%2FLb5nYBw6gOTv%2BihvQf%2F2Lkxq2KmJGQZ%2BUergCUt9yL4cS6ghwhZZ3BOIf1zmfhzP1nMI2vBkLzvfqC9inLPIuwUQiqpc%2BFLiIerBynazwSuT9jZ0ri6s2Lz16auwqWzH08U3Qq8xYz4S1zO7aZ0n32JCWUPLXr1Lasm5pyo9qt8fsTkI7S7H0YfxQp1xuSjJum0kpjqhvZedIBBzWlylZvrLSXTk76htL62aXwtbT6fWh5ezNieAt%2B14bf%2F0eUsqOWg3FjzEJ6l0f24K1vjpo
![](https://prod-files-secure.s3.us-west-2.amazonaws.com/871f1661-80b8-4d0c-ac3b-2adfc6ff4c66/b1cbe17b-022d-47d7-89ad-2f18060e88e2/applying_the_use_case_pattern_with_rails.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=ASIAZI2LB466S7MFUMTW%2F20260611%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20260611T172002Z&X-Amz-Expires=3600&X-Amz-Security-Token=IQoJb3JpZ2luX2VjEDkaCXVzLXdlc3QtMiJIMEYCIQDOz0YR4iHjxIwnyVYYPaqxazHcsVAhzex0Uk80GUhZigIhAMDx3XC1Z3ka%2Brdk9iZsDCXlMCD0UDx94Tzl2fokHxn%2BKv8DCAEQABoMNjM3NDIzMTgzODA1IgxJ61jrLhSzP5tKoIIq3AN6%2FM1JRJXKejJGPe9IQPq4s9w8UGg%2FqwH8UmIvAKuxrnryZr9L4Cpv%2B1TBK2K%2BTh6Dg5kDH95bbfVSlwSI3QNR4V5FQMh0bX%2B0wxBCr2VxiR6e6P2NAL%2FLb5nYBw6gOTv%2BihvQf%2F2Lkxq2KmJGQZ%2BUergCUt9yL4cS6ghwhZZ3BOIf1zmfhzP1nMI2vBkLzvfqC9inLPIuwUQiqpc%2BFLiIerBynazwSuT9jZ0ri6s2Lz16auwqWzH08U3Qq8xYz4S1zO7aZ0n32JCWUPLXr1Lasm5pyo9qt8fsTkI7S7H0YfxQp1xuSjJum0kpjqhvZedIBBzWlylZvrLSXTk76htL62aXwtbT6fWh5ezNieAt%2B14bf%2F0eUsqOWg3FjzEJ6l0f24K1vjpo6J9uexQ6tno085WEpUu52AIzJyrA6tnvTgL560m99yg6J0Tuzy3i7nm6aL%2B0Djz5KcnP6EpgNdwgVMRCSPHXGwA8xgEbkOYhp29IVJ9Wvfj6MSgsABJVpHRzCmKkx9Tv%2Fdk3ScKvmgPXkVtkyPCHUVjSs4AM2AxwWzMJmIYUs8XGWkt%2BdX0sjpcVAHQekbXjTejCGn58%2F4vOiRwShXPIarLNG1VmPQdLkww8QQxLjwaSvgutkTCewKvRBjqkAcJbJktvo4LhXz40v%2Btq05OBxju%2F%2FfLe1%2BZeRp4fzK8FTS%2FkOGGS8r44mS90NM6GgZOF5IJ%2BLTdRNHBKOx%2FbxCuYOIAp1WgdgtN1IZtURndOWtVeX0pxwELAT0o6kyv%2F4G3UiPfDFouk5ufrjALiQZ4MJh%2FrPZK%2BZZlNxhk6Dgt9hj5PRg450qYgw3dlQBHnXl7HthTJ3%2FZl5kvl5HyRMm%2Fl%2BfSC&X-Amz-Signature=c8f9907ddd67deb786fdd0987b5ad69c66a49b5fc50849f858e772e824928a4b&X-Amz-SignedHeaders=host&x-amz-checksum-mode=ENABLED&x-id=GetObject) A common problem while working with Rails is to decide where to place the logic from our features. The logic is often placed in the Controllers, Models, or if we are lucky in a Service Object. So if we have Service Objects then why do we need Use Cases? Follow me in this article to discover the benefits of this pattern. ## Use Case ### Definition A use case is a list of actions or event steps typically defining the interactions between a role and a system to achieve a goal. It’s worth mentioning that this pattern is applied in many different ways and has alternative names. We can find it as Interactors, Operators or Commands, but in the Ruby community we stick with Use Case. Every implementation is different but with the same purpose: to serve a user's use case of the system. Even if in our project we are not defining the requirements using Use Cases and UML this pattern is still useful to structure the business logic in a practical way. ### Rules Our Use Cases must be: - Framework agnostic - Database agnostic - Responsible for only one thing (define the steps to achieve the user’s goal) ### Benefits - Readability: Easy to read and understand since the steps are clearly defined. - Decoupling: Move the logic from Controllers and Models and create a new level of abstraction. - Visibility: The codebase reveals the features available in the system. ## Into Practice Let’s take the example of a user that wants to purchase something in our system. ```plain text module UseCases module Buyer class Purchase def initialize(buyer:, cart:) @buyer = buyer @cart = cart end def call return unless check_stock return unless create_purchase notify end private attr_reader :buyer, :cart def check_stock Services::CheckStock.call(cart: cart) end def create_purchase Services::CreatePurchase.call(buyer: buyer, cart: cart).call end def notify Services::NotifyBuyer.call(buyer: buyer) end end end end ``` As you may see in this code example, we created a new Use Case called Purchase. We defined only one public method call. Inside the call method, we find pretty basic steps to make a purchase, and all the steps are defined as private methods. Every step is calling a Service Object, this way our Use Case is only defining the steps to make a purchase and not the logic itself. This gives us a clear picture of what can be done in our system (make a purchase) and the steps to achieve that. Now we are ready to call our first Use Case from a controller. ```plain text class Controller def purchase UseCases::Buyer::Purchase.new( buyer: purchase_params[:buyer], cart: purchase_params[:cart] ).call ... end ... end ``` From this perspective, the Use Case looks pretty much like a Service Object but the purpose is different. A Service Object accomplishes a low-level task and interacts with different parts of the system like the Database while the Use Case creates a new high-level abstraction and defines the logical steps. ## Improvements Our first Use Case works but could be better. How could we improve it? Let’s make use of the dry gems. In this case we are going to use dry-transaction. First let’s define our base class. ```plain text class UseCase include Dry::Transaction class << self def call(**args) new.call(**args) end end end ``` This will help us to pass attributes to the UseCase transaction and use them. Then we are ready to re-define our Purchase Use Case. ```plain text module UseCases module Buyer class Purchase < UseCase step :check_stock step :create_purchase step :notify def call(buyer:, cart:) @buyer = buyer @cart = cart super end private attr_reader :buyer, :cart def check_stock return Failure() unless Services::CheckStock.call(cart: cart) Success() end def create_purchase return Failure() unless Services::CreatePurchase.call( buyer: buyer, cart: cart ).call Success() end def notify return Failure() unless Services::NotifyBuyer.call(buyer: buyer) Success() end end end end ``` With the new changes, we can see in a clear way how our steps are defined and we can manage the result of every step with Success() and Failure(). We are ready to call our new Use Case in the controller and prepare our response depending on the final result. ```plain text class Controller def purchase UseCases::Buyer::Purchase.new.call( buyer: purchase_params[:buyer], cart: purchase_params[:cart] ) do |result| result.success do ... end result.failure do ... end end ... end ... end ``` This example could be improved even more with validations but this is enough to show the power of this pattern. ## Conclusions Let’s be honest here, the Use Case pattern is pretty simple and looks a lot like a Service Object but this level of abstraction can make a big change in your application. Imagine a new developer joining the project and opening the folder use_cases, as a first impression he will have a list of all the features available in the system and after opening one Use Case he will see all the necessary steps for that feature without going deep in the logic. This sense of order and control is the major benefit of this pattern. Take this in your toolbox and maybe in the future you will make good use of it. Read More

Visibility

Visible to everyone

Reading Status

Related Bookmarks

My Note


Saved!

Annotations

Export as Markdown

Attachments

+ Annotate selection

Add Annotation