views:

17

answers:

1

I'm trying to use a class as a before filter for multiple controllers. Because the filter must do slightly different things based on which controller is calling it, it seems like I need to use a class as a filter in order to get the controller passed in to filter.

So far, I have something like

class ShowFilter
def self.filter(controller)
  c_name = controller.controller_name
  object_id = controller.params[:id]
  case c_name
    when "articles"
      article = Article.find(object_id)
      unless curr_user.can_see?(article)
        controller.redirect_to(:controller => "articles", :action => "index")
      end
    when "images"
      image = Image.find(object_id)
      unless curr_user.can_see?(image)
        controller.redirect_to(:controller => "images", :action => "index")
      end
  end
end

This class would be called as a :before_filter on the show action in the articles and images controllers.

My problem is that I get an error saying that 'redirect_to' is a protected method of whatever controller gets passed into the filter.

If I call

redirect_to(:controller => "images", :action => "index")

instead of

controller.redirect_to(:controller => "images", :action => "index")

I get an "undefined method 'redirect_to' for ShowFilter:Class" error.

If I define my class as

class ShowFilter < ApplicationController

I still get an undefined method error. I am having the exact same issues accessing the flash as well.

Is there a way to redirect inside of a filter class? Should I be using a different method to filter in order to be able to redirect and access the flash?

A: 

You could use controller.send(:redirect_to, "your url") to bypass the protected level of the method.

Tanel Suurhans
Thanks, Tanel. Do you have any good links regarding how controller.send works? I'm still trying to set the flash, and I can't figure it out.
Sam P