Rails controller 中有大量重复代码,怎么重构

zealinux · October 03, 2012 · Last by zfjoy520 replied at October 10, 2012 · 3375 hits

有很多下面重复的代码,大家是怎么重构的?

respond_to do |format|
   format.html
   format.json { render json: @product }
 end

个人觉得没必要对这些代码做过多的精简

刚刚在 railscasts 里面看到的:

class UsersController < ApplicationController
  respond_to :html, :json

  # Other actions omitted.

  def update
    @user = User.find(params[:id])
    @user.update_attributes(params[:user])
    respond_with @user
  end

end

可以试试这个 gem:inherited_resources https://github.com/josevalim/inherited_resources

#2 楼 @uudui 同感,默认的方式已经很清晰了

gem 用太多了不好维护啊

不要为了重构而重构

重构不是看到代码重复就是重构。 重构容易变化的地址,重构抽象集中业务逻辑,或者是某些固定的处理流程。

哈哈。重构到最后隔一个月连自己都看不懂了。

You need to Sign in before reply, if you don't have an account, please Sign up first.