我在我的應用程序中有一個bazillion控制器,我想知道如何使用一些元編程來使維護更少。這是有效的,但它的eval形式的危險刺激:Eval alternative
def plural_action(method_name)
class_name = self.class.to_s.gsub(%r{^(\w*)Controller}) {|s| $1 }
@title = "#{method_name.to_s.titlecase} of #{class_name}"
eval "@q = #{class_name.singularize}.where(:client_id => current_user.client_id).search(params[:q])"
eval "@#{class_name.downcase} = @q.result(:distinct => true).paginate(:page => params[:page])"
eval "session[:query] = @#{class_name.downcase}.map(&:id)"
eval "respond_with(@#{class_name.downcase})"
end
我可以做到這一點,而不使用eval?我已經修改了instance_variable_set,send和const_get,但目前還沒有運氣。
下面是我想要評估方法的一個示例。
def index
@title = "Index of Books"
@q = Book.where(:client_id => current_user.client_id).search(params[:q])
@books = @q.result(:distinct => true).paginate(:page => params[:page])
session[:query] = @books.map(&:id)
respond_with(@books)
end
[decent_exposure](https://github.com/voxdolo/decent_exposure)gem可能會讓你成爲那裏的一部分,儘管它不會完全解決問題。 – 2011-12-20 12:08:03