【译】替换复杂的创建方法(Creation)为工厂方法(Factory Method)

Saturday, July 24, 2010

原文:
http://rails-bestpractices.com/posts/6-replace-complex-creation-with-factory-method

有时候我们需要在控制器中通过表单参数,当前用户属性和其他逻辑来创建一个复杂的model对象,这样把控制器写得又长又丑,
所以我们需要把它以工厂方法的方式移到模型中去

丑陋的...

class InvoicesController < ApplicationController
  def create
    @invoice = Invoice.new(params[:invoice])
    @invoice.address = current_user.address
    @invoice.phone = current_user.phone
    @invoice.vip = (@invoice.amount > 1000)

    if Time.now.day > 15
      @invoice.delivery_time = Time.now + 2.month
    else
      @invoice.delivery_time = Time.now + 1.month
    end

    @invoice.save
  end
end

这样的逻辑去创建一个invoice太复杂了, 这样使得控制器难以阅读,
而且控制器不需要知道太多的事情关于创建这个模型对象,我们需要把创建一个invoice的逻辑移到Invoice模型中.

重构...

class Invoice < ActiveRecord::Base
  def self.new_by_user(params, user)
    invoice = self.new(params)
    invoice.address = user.address
    invoice.phone = user.phone
    invoice.vip = (invoice.amount > 1000)

    if Time.now.day > 15
      invoice.delivery_time = Time.now + 2.month
    else
      invoice.delivery_time = Time.now + 1.month
    end
  end
end



class InvoicesController < ApplicationController
  def create
    @invoice = Invoice.new_by_user(params[:invoice], current_user)
    @invoice.save
  end
end

现在我们在Invoice模型中定义了一个new_by_user的方法,它负责创建invoice,
这样在控制器中只要调用new_by_user方法就可以创建invoice对象了

请记住 "瘦控制器, 胖模型"这一原则!

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top