Alias Method Chain in before_filter

Hi all,

I have the follow code to trap some exceptions in a controller.

The code seems to run fine on my development machine but on
production, it goes into an infinitely loop (eventually a stack
overflow) trapping at the create_without_jazz() method call. Does
anyone see a potential problem with the the way I’m handling
the exceptions? (note: render() is not in the correct context, so I
couldn’t use around filter). Thanks in advance for all your help.

Pastie: Parked at Loopia

class FooBarsController < ApplicationController

before_filter(:only => :create) do
class_eval {
def create_with_jazz
begin
create_without_jazz()
rescue Exception => e
render :text => ‘error’
end
end

    alias :create_without_jazz :create
    alias :create :create_with_jazz
}

end

def create
raise ‘foo bar create’
render :text => ‘foo bar’
end

end

On 7/19/07, David D. [email protected] wrote:

      rescue Exception => e
raise 'foo bar create'
render :text => 'foo bar'

end

end

Hi David,

I don’t really understand what you’re trying to do here. Why not just
catch the exception in #create? I’d say it’s blowing the stack in
production mode because the class is not being reloaded on every
request (which it is by default in development). Consequently, your
class_eval gets run more than once on your controller class.

There are of course workarounds, depending on what you’re trying to
accomplish. Could you elaborate on that more? Also note that if
you’re just trying to catch unhandled exceptions, it’s probably easier
to define #rescue_action (see docs).

Regards,
George.

Hi George,

Thanks for the reply! The primary reason I did it this way was
because I wanted a generic way to handle exceptions that’s flexible
enough to allow custom rendering on a per action basis. For instance
you have a lot of existing code that had to deal with various contents
(e.g. one controller per content). And you needed to be able to
blacklist a user and take away all his/her creation rights. You (at
least me) don’t want to go into each action of each controller to
inject control logics all over the place. So I came up with this
cheap way to raise an exception at the model level whenever someone
(the blacklisted user) tries to save a content (raise in
before_save). I will then catch it with the before_filter as you’ve
seen above. I guess I can use rescue_action and filter down the
actions list based on my exception. Any thoughts on the way I’m
approaching this problem? I somehow I feel kinda dirty mixing model
and controller this way. Opinions and comments are welcome!

David