我在我的应用程序中有一个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