Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

before_filter and respond_to formats

In a controller in my Rails app, I can do this:

before_filter :login_required, :except => :index

But I would like to apply the filter not only based on the action name but on the format of the request. In other words, I would like to do something like this:

before_filter :login_required, :except => {:action => :index, :format => :js}

Is this possible?

like image 433
gdelfino Avatar asked Apr 30 '09 23:04

gdelfino


2 Answers

You'll need to roll your own a bit. Try this as a starting point.

 before_filter :login_required, :except => [:index]

 before_filter(:only => :index) do |controller|
   login_required unless controller.request.format.js?
 end
like image 172
jdl Avatar answered Nov 15 '22 03:11

jdl


Remember, you can extract the lambda to a method too. This can help with readability. It can also make it easier to use the same check on multiple filters.

before_filter :login_required, except: :index, unless: :js_request?

private

def js_request?
  request.format.js?
end
like image 16
Kyle Tolle Avatar answered Nov 15 '22 02:11

Kyle Tolle