Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Clean Architecture in Ruby - Tropical Ruby 2015

bezelga
March 07, 2015

Clean Architecture in Ruby - Tropical Ruby 2015

What, how and when to apply Clean Architecture in Ruby. Using Rails as a delivery mechanism.

I wrote an article about it here: https://medium.com/@fbzga/clean-architecture-in-ruby-7eb3cd0fc145

bezelga

March 07, 2015
Tweet

More Decks by bezelga

Other Decks in Technology

Transcript

  1. CHAPTERS 1. What is Clean Architecture? 2. How to use

    it with Rails? 3. When to use it?
  2. the ENTRY POINT 1. Create project 2. Define API 3.

    Define behavior 4. Entry point
  3. the USE CASE 1. Create project 2. Define API 3.

    Define behavior 4. Entry point 5. Use case
  4. module Lannister module UseCases class TransferMoney def transfer return false

    if get_balance(account_id: source_account_id) < amount trade_repo.persist Entities::Trade.new(account_id: source_account_id, amount: - amount) trade_repo.persist Entities::Trade.new(account_id: destination_account_id, amount: amount) end end end end
  5. the TRADE Entity 1. Create project 2. Define API 3.

    Define behavior 4. Entry point 5. Use case 6. Entity
  6. require 'active_model' module Lannister module Entities class Trade include ActiveModel::Model

    attr_accessor :id, :account_id, :amount, :date validates_presence_of :account_id, :amount, :date end end end
  7. the REPOSITORY 1. Create project 2. Define DSL 3. Define

    behavior 4. Entry point 5. Use case 6. Entity 7. Repository
  8. 1. Create project 2. Define API 3. Define behavior 4.

    Entry point 5. Use case 6. Entity 7. Repository DONE!
  9. class TransferMoneyController < ApplicationController before_action :load_balance def create if Lannister.transfer_money(source_account_id:

    source_account_id, destination_account_id: destination_account_id, amount: amount) redirect_to new_transfer_money_path else flash[:error] = 'Not enough money on the source account' render :new end end private def load_balance @balance = Lannister.get_balance(account_id: current_account_id) end end
  10. NOT so good • more files to handle in your

    cognitive memory • over engineering when the domain logic is close to the view • getting out of the rails way may hurt in the beginning
  11. • delay decisions until the last responsible moment • makes

    clear app’s intent (not how it’s built) • business rules isolated from the web, framework and database • consequence: tests running faster the cool STUFF