before_filter and respond_to formats

2020-02-24 12:52发布

问题:

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?

回答1:

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


回答2:

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


回答3:

Another way, which I think is cleaner than the accepted answer, is to use the if or unless options with a lambda. I just like having the method name listed as a symbol so it's standardized with the other controller filters. This works in Rails 3 and up.

before_filter :login_required, except: :index,
  unless: -> { |controller| controller.request.format.js? }