有条件的before_action / before_filter的文档 [英] Documentation for conditional before_action/before_filter

查看:215
本文介绍了有条件的before_action / before_filter的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在最近的代码审查期间,我被问及是否需要 proc 。答案似乎是是,但这是一个合理的问题,我打算通过参考Rails文档或指南或使用条件符号与 before_filter (现在是 before_action 的别名)。



我找不到任何内容。有没有描述这种用法的(当前和官方)指南或文档? 操作控制台指南提到:仅 / :除了,但不是:如果 / :除非



没有这个,代码中有什么地方可以指出这一点吗?简要介绍这里,但这更多关于如何:只有:除了,而不是:if :除非

解决方案

在Rails指南中找到: http://guides.rubyonrails.org/active_record_callbacks.html#conditional-callbacks



发现一个 Proc 并不总是需要它工作。


:if :除非选项,可以采取符号,一个字符串,一个 Proc Array


所以在你的情况下,你可能会摆脱

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

有时在Rails文档中查找内容可能会很痛苦,但至少这样的问题会使事情变得更容易随着时间的推移,StackOverflow被很好地编入索引并具有很高的搜索排名。


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 whether 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. Is there a (current and official) guide or documentation that describes this usage? 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.

解决方案

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.

这篇关于有条件的before_action / before_filter的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆