代码之家  ›  专栏  ›  技术社区  ›  daniel

这个太干了,我要下船吗?

  •  1
  • daniel  · 技术社区  · 14 年前

    我一直在烘干一些代码,其中一个重构如下:
    我有3个控制器(建筑公司、房地产公司、人),所有这些控制器都有以下模式:

    
    class ConstructionCompaniesController &lt 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 &lt 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   
    

    正如您所看到的,正确的用户在每个控制器中重复出现。
    因此,我在帮助程序(包括所有帮助程序)中所做的,创建了一个方法:

    
    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 &lt ApplicationController
    
      before_filter :only => [:edit, :update] do |controller| correct_user_for_seller_of_controller(controller) end           
    
    
    
    class RealEstateCompaniesController &lt ApplicationController
    
     before_filter :only => [:edit, :update] do |controller| correct_user_for_seller_of_controller(controller) end           
    
    

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

    3 回复  |  直到 14 年前
        1
  •  4
  •   Harish Shetty    14 年前

    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
    
        2
  •  1
  •   Matchu    14 年前

    controller_name

        3
  •  1
  •   Jakub Hampl    14 年前