ruby 这是Jim Weirich的“与Rails脱钩”谈话的摘录,讲解了如何应用六边形设计模式制作前夕

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 这是Jim Weirich的“与Rails脱钩”谈话的摘录,讲解了如何应用六边形设计模式制作前夕相关的知识,希望对你有一定的参考价值。

# 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

以上是关于ruby 这是Jim Weirich的“与Rails脱钩”谈话的摘录,讲解了如何应用六边形设计模式制作前夕的主要内容,如果未能解决你的问题,请参考以下文章

求名牌太阳镜Maui jim 的详细资料

Jim Henson的个人简介

芯片之神Jim Keller

攻防世界(解密篇Crypto)---混合编码

在逗号分隔的列表中查找经理

ruby 我无法相信这是有效的Ruby语法。附: - 我喜欢Ruby