Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Implement a Redirect on All Requests (on certain conditions)?

I want to set something up so that if an Account within my app is disabled, I want all requests to be redirected to a "disabled" message.

I've set this up in my ApplicationController:

class ApplicationController < ActionController::Base
  before_filter :check_account

  def check_account
    redirect_to :controller => "main", :action => "disabled" and return if !$account.active?
  end
end

Of course, this doesn't quite work as it goes into an infinite loop if the Account is not active. I was hoping to use something like:

redirect_to :controller => "main", :action => "disabled" and return if !$account.active? && @controller.controller_name != "main" && @controller.action_name != "disabled"

but I noticed that in Rails v2.1 (what I'm using), @controller is now controller and this doesn't seem to work in ApplicationController.

What would be the best way to implement something like this?

like image 924
Dan Harper Avatar asked Dec 30 '22 10:12

Dan Harper


1 Answers

You have several options.

If your action method "disabled" is uniquely named in the scope of the application, you can add an exception to the before_filter call, like this:

before_filter :check_account, :except => :disabled

If you want to check specifically for the controller and action in the filter, you should note that this code is already part of the controller object. You can refer to it as "self," like so:

  def check_account
    return if self.controller_name == "main" && self.action_name == "disabled"

    redirect_to :controller => "main", :action => "disabled" and return if !$account.active?
  end

Finally, if you like, you can overwrite the filter method from within MainController.rb:

  def check_account
    return if action_name == "disabled"
    super
  end
like image 131
Ian Terrell Avatar answered Jan 13 '23 14:01

Ian Terrell