Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "proc" required with conditional before_action/before_filter?

Behold, a before_filter:

class ThingController < ApplicationController   before_filter :check_stuff, :if => proc {Rails.env.production?} end 

During a recent code review, I was asked, "Is the proc is required for this to work?" The answer appears to be 'yes', but it's a reasonable question, and I had intended to answer it by referring to the Rails docs or guides or something on the use of conditionals with before_filter (now an alias of before_action).

I couldn't find any. The Action Controller Guide mentions :only/:except, but not :if/:unless.

Failing that, is there somewhere in the code I can point to that covers this? It's mentioned briefly here, but that's more about how :only and :except are handled, rather than :if or :unless.

like image 816
MrTheWalrus Avatar asked Apr 29 '14 15:04

MrTheWalrus


People also ask

What is Before_action in Ruby?

before_filter/before_action: means anything to be executed before any action executes. Both are same. they are just alias for each other as their behavior is same.

What does Before_action do in Rails?

The only option of before_action defines one action OR a list of actions when the method/block will be executed first. The set_newsletter_email method will be called just before the show and edit actions. The opposite option except define when NOT to execute the method/block.


2 Answers

Found it on Rails Guides: http://guides.rubyonrails.org/active_record_callbacks.html#conditional-callbacks

Turns out a Proc isn't always required for it to work.

the :if and :unless options, which can take a symbol, a string, a Proc or an Array.

So in your case you could probably get away with

before_action :check_stuff, if: "Rails.env.production?" 

Finding things in Rails documentation can be a pain sometimes, but at least questions like this make things easier to find over time since StackOverflow is well indexed and has high search rankings.

like image 198
Dennis Avatar answered Sep 20 '22 17:09

Dennis


From Rails 5.2 onwards, the current accepted answer is no longer be valid, and passing a string to the conditional will fail.

DEPRECATION WARNING: Passing string to :if and :unless conditional options is deprecated and will be removed in Rails 5.2 without replacement.

Going forward, a proc is now the best way to add a conditional like in the original question:

class ThingController < ApplicationController   before_action :check_stuff, :if => proc {Rails.env.production?} end 
like image 20
Amin Shah Gilani Avatar answered Sep 22 '22 17:09

Amin Shah Gilani