Is “proc” required with conditional before_action/before_filter?

后端 未结 4 1084
你的背包
你的背包 2021-02-05 00:05

Behold, a before_filter:

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


        
相关标签:
4条回答
  • 2021-02-05 00:55

    I would recommend using staby lambda. If you want know, WHY? Please read this

    class ThingController < ApplicationController
      before_action :check_stuff, if: -> { Rails.env.production? }
    end
    

    which is almost equivalent to Upvote Me's answer.

    0 讨论(0)
  • 2021-02-05 00:56

    i have done this on my code while ago. I hope that example helps to you. If you can use if statement but that should point to another method like I did here.

    class Admin::ArticlesController < ApplicationController
      before_filter :deny_access, :unless => :draft_and_admin?
    
      def show
        @article = Article.find(params[:id])
      end
    
      protected
    
      def draft_and_admin?
        Article.find(params[:id]).draft? && current_user.admin?
      end
    end
    
    0 讨论(0)
  • 2021-02-05 01:00

    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
    
    0 讨论(0)
  • 2021-02-05 01:03

    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.

    0 讨论(0)
提交回复
热议问题