我的应用程序中有大量的控制器,我想知道是否可以使用一些元编程来减少维护的麻烦。这是可行的,但它以eval的形式充满了危险:
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,但到目前为止还没有成功。
下面是我希望eval方法的一个示例。
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发布于 2011-12-20 17:24:47
有一个很棒的方法constantize,它将一个字符串转换成它所表示的常量(其中类类型就是一个例子)。考虑到这一点,我认为您可以将您的方法重写为:
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}"
@q = class_name.singularize.constantize.where(:client_id => current_user.client_id).search(params[:q])
self.instance_variable_set("@#{class_name.downcase}", @q.result(:distinct => true).paginate(:page => params[:page]))
session[:query] = self.instance_variable_get("@#{class_name.downcase}").map(&:id)
respond_with(self.instance_variable_get("@#{class_name.downcase}"))
end发布于 2011-12-20 17:41:21
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}"
@q = class_name.singularize.constantize.where(:client_id => current_user.client_id).search(params[:q])
instance_variable_set class_name.downcase, @q.result(:distinct => true).paginate(:page => params[:page])
session[:query] = @q_result.map(&:id)
respond_with(@q_result)
endhttps://stackoverflow.com/questions/8573123
复制相似问题