views:

418

answers:

4

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?

A: 

If theres not too many overrides then just put the if in the redirect filter

if action != disabled redirect() end

flukus
+4  A: 

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
Ian Terrell
+3  A: 

You could also use a skip_before_filter for the one controller/method you don't want to have the filter apply to.

Thanatos
I think that may be the cleanest way to implement it. Thank you!
Dan Harper - Leopard CRM
+1  A: 

How about first getting rid of that global variable $account. You are basically setting yourself up for some serious bugs by using a global. Just use an instance variable instead @ or better yet create a method on ApplicationController called current_account which access the @current_account instance variable.

Eric Allam
Hey Eric, thanks for the heads-up. I was sure there was a better way to do it, I think the current_account method would be a great way to go. Cheers!
Dan Harper - Leopard CRM