Last active
November 2, 2024 00:52
-
-
Save dhh/4849a20d2ba89b34b201 to your computer and use it in GitHub Desktop.
This is an extraction from Jim Weirich's "Decoupling from Rails" talk, which explained how to apply the hexagonal design pattern to make every layer of your application easily unit testable (without touching the database etc). It only seeks to extract a single method, the EmployeesController#create method, to illustrate the design damage that's …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Original Rails controller and action | |
class EmployeesController < ApplicationController | |
def create | |
@employee = Employee.new(employee_params) | |
if @employee.save | |
redirect_to @employee, notice: "Employee #{@employee.name} created" | |
else | |
render :new | |
end | |
end | |
end | |
# Hexagon-inspired, test-induced, damaged version | |
class EmployeesController < ApplicationController | |
def create | |
CreateRunner.new(self, EmployeesRepository.new).run(params[:employee]) | |
end | |
def create_succeeded(employee, message) | |
redirect_to employee, notice: message | |
end | |
def create_failed(employee) | |
@employee = employee | |
render :new | |
end | |
end | |
class CreateRunner | |
attr_reader :context, :repo | |
def initialize(context, repo) | |
@context = context | |
@repo = repo | |
end | |
def run(employee_attrs) | |
@employee = repo.new_employee(employee_attrs) | |
if repo.save_employee | |
context.create_succeeded(employee, "Employee #{employee.name} created") | |
else | |
context.create_failed(employee) | |
end | |
end | |
end | |
class EmployeesRepository | |
def new_employee(*args) | |
Biz::Employee.new(Employee.new(*args)) | |
end | |
def save_employee(employee) | |
employee.save | |
end | |
end | |
require 'delegate' | |
module Biz | |
class Employee < SimpleDelegator | |
def self.wrap(employees) | |
employees.wrap { |e| new(e) } | |
end | |
def class | |
__getobj__.class | |
end | |
# Biz logic ... AR is only a data-access object | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Let's all be civil.