Conditionally apply skip_before_filter with: if => condition in rails 4

I have an Events controller on which I want to skip authentication if the event is open.

In my ApplicationController , I have this call to develop authenticate_user!

 class ApplicationController < ActionController::Base before_action :authenticate_user! end 

now, inside the "My Events" table, I have a logical field called public . I use this to check if an event is open or not. Like it in EventsController

 class EventsController < ApplicationController skip_before_action :authenticate_user!, only: :show, if: Proc.new { :is_public? } end 

But for some reason this did not work. so I had to do this:

 class EventsController < ApplicationController skip_before_action :authenticate_user!, only: :show before_action :authenticate_user!, unless: :is_public? def is_public? @event.present? && @event.is_public end end 

This works as expected and will skip authentication if @event.public = true , because the above repeats before_filter with the opposite condition after skipping.

I am wondering:

  • what did i do right?
  • This affects performance. if so, is there a better way?
+6
source share
1 answer

the documentation on rails for callbacks (before, after, around the action) is actually pretty bad. see this similar question: skip_before_filter ignores conventions

therefore, I always refer to the guide rails. the part that will be of interest to you here: http://guides.rubyonrails.org/action_controller_overview.html#other-ways-to-use-filters

I'm not quite sure that this will work with a pass filter, but it's worth a try.

should not affect performance simply by calling different filters. Performance problems typically arise from extensive database queries or other external system calls.

My main problem here was that it’s rather difficult to understand why so many before_action events happen ...

+6
source

Source: https://habr.com/ru/post/955870/


All Articles