views:

31

answers:

1

Following code works just fine.

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

end

However I wanted to refactor the code and put this functionality in a lib since my application controller has grown large.

This is what I came up with and it works.

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

end end

The solution works. However I do not really like dong eval. I was wondering if there is a better way to achieve the same goal.

+1  A: 

Have you tried:

base.send(:rescue_from, ...)
Kenny
base.send(:rescue_from,...) keeps the code in the controller. My goal is take code out of controller and in the lib.
Neeraj Singh
It doesn't need to be kept in the controller: you should be able to substitute base.send(:eval,tmp) with my suggestion, within the self.included method of the RescueFromRecordNotFound module.
Kenny