-
Notifications
You must be signed in to change notification settings - Fork 277
Replace Complex Creation with Factory Method
Richard Huang edited this page Aug 15, 2010
·
3 revisions
Please go to http://rails-bestpractices.com/posts/6-replace-complex-creation-with-factory-method
Before:
class InvoiceController < 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
After:
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