我已经干燥一些代码,这refactors之一是如下:
我有3个控制器(ConstructionCompanies,RealEstateCompanies,人)所有这些具有下列模式:这太干了,我会过度?
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
我喜欢的事实,现在是干的,但问题是这对我来说似乎有点复杂,很难理解。我走得太远了吗?
@KandadaBoggu:我甚至没有看到这一点。哇,很好抓xD – Matchu 2010-11-08 03:50:41
这是一个很大的A **,很难错过... :-) – 2010-11-08 03:54:16