这太干了,我会过火吗?

时间:2010-11-08 03:31:25

标签: ruby-on-rails ruby-on-rails-3 dry

我一直在干掉一些代码,其中一个重构如下:
我有3个控制器(ConstructionCompanies,RealEstateCompanies,People),所有这些控制器都具有以下模式:


class ConstructionCompaniesController < ApplicationController
before_filter :correct_user, :only => [:edit, :update]

private
   def correct_user
      @company = ConstructionCompany.find(params[:id]) 
      if(current_user.owner != @company.user)
        redirect_to(root_path)
      end
    end   

class RealEstateCompaniesController < ApplicationController
  before_filter :correct_user, :only => [:edit, :update]
...

private
   def correct_user
      @company = RealEstateCompany.find(params[:id]) 
      if(current_user.owner != @company.user)
        redirect_to(root_path)
      end
    end   

如您所见,每个控制器中都重复了correct_user 所以我在我帮助中做了什么,包括所有这些我创建了一个方法:


def correct_user_for_seller_of_controller(controller)
    #"User".classify will return the class User etc.
    @seller = controller.controller_name.classify.constantize.find(params[:id])     
    redirect_to(root_path) unless (current_user == @seller.user)
  end                            

知道我拥有的每个控制器:


class ConstructionCompaniesController < ApplicationController

  before_filter :only => [:edit, :update] do |controller| correct_user_for_seller_of_controller(controller) end           


class RealEstateCompaniesController < ApplicationController

 before_filter :only => [:edit, :update] do |controller| correct_user_for_seller_of_controller(controller) end           

我喜欢现在干的事实,但问题是对我来说似乎有点复杂,难以理解。我走得太远了吗?

3 个答案:

答案 0 :(得分:4)

correct_user方法添加到ApplicationController类。

class ApplicationController
  def correct_user_for_seller_of_controller
    #"User".classify will return the class User etc.
    @seller = controller_name.classify.constantize.find(params[:id])     
    redirect_to(root_path) unless (current_user == @seller.user)
  end  
end

在您的控制器中使用新方法作为过滤方法:

class RealEstateCompaniesController < ApplicationController

 before_filter :correct_user_for_seller_of_controller, :only => [:edit, :update]

end

答案 1 :(得分:1)

清理它绝对是件好事。我认为你可能会使事情变得比必要的稍微复杂一点,但是,所有的事情都是如此。

如果在控制器的实例上运行过滤器,则无需将控制器传递给自身。只需在方法中调用controller_name,就可以了。

答案 2 :(得分:1)

我个人会干它并将过滤器移到超类(或AppplicationController)。

方法本身也可以简化。例如,使用一些内省。