2009-08-14 44 views
0

以下代码工作得很好。如何将实时代码方法(如'has_man')添加到库中

class ApplicationController < ActionController::Base 
rescue_from ActiveRecord::RecordNotFound, :with => :bad_record 
def bad_record 
    redirect_to root_url 
end 

但是我想重构代码和一个lib把这个功能,因为我的应用程序控制器已经成长大。

这就是我想出来的,它的工作原理。

class ApplicationController < ActionController::Base 
include RescueFromRecordNotFound 
end 
\#lib/rescue_from_record_not_found.rb 
module RescueFromRecordNotFound 
def self.included(base) 
    tmp = "rescue_from ActiveRecord::RecordNotFound, :with => :bad_record" 
    base.send(:eval,tmp) 
    base.send(:include, InstanceMethods) 
end 
module InstanceMethods 
    def bad_record 
    redirect_to root_url 
    end 

末 结束

解决方案的工作。不过我并不喜欢dong eval。我想知道是否有更好的方法来实现相同的目标。

回答

1

你试过:

base.send(:rescue_from, ...) 
+0

base.send(:rescue_from,...)保持代码的控制器。我的目标是从控制器和lib中取出代码。 – 2009-09-09 19:58:26

+0

它不需要保存在控制器中:您应该能够用我的建议在RescueFromRecordNotFound模块的self.included方法中替换base.send(:eval,tmp)。 – Kenny 2009-09-09 23:02:51

相关问题