before_filter and respond_to formats

2020-02-24 12:54发布

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?

3条回答
冷血范
2楼-- · 2020-02-24 13:37

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
查看更多
神经病院院长
3楼-- · 2020-02-24 13:49

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
查看更多
孤傲高冷的网名
4楼-- · 2020-02-24 13:53

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? }
查看更多
登录 后发表回答