Rails验证:if => Proc.new还是lambda? [英] Rails validation :if => Proc.new or lambda?
问题描述
我发现在验证方法的:if选项中看到的所有示例(包括rails文档)中,例如都使用Proc.new而不是lambda
I have found that in all examples (include rails documentation) that I have seen for the :if option of validation methods uses Proc.new instead of lambda, for example
class Foo < ActiveRecord::Base
validates_presence_of :name, :if => Proc.new{|f| .... } # why not lambda here?
end
有什么原因吗? 据我所知lambda
is there any reason for this? As far as I know, lambda
- 对参数的要求更严格.
- lambda块中的return语句也从该块返回,而不是从调用函数返回.
对于上述:if选项,这似乎都是合乎需要的行为,我有什么想念的吗?
Both seems to be desirable behavior for :if option mentioned above, is there anything I am missing?
推荐答案
对于上述:if选项,这似乎都是合乎需要的行为,我有什么想念的吗?
Both seems to be desirable behavior for :if option mentioned above, is there anything I am missing?
我猜是:
允许Procs更为可取,因为它们不关心参数的数量.因此,我可以轻松编写以下任何内容:
It's more desirable to allow Procs as they don't care about the number of arguments. So I could easily write any of the below:
validates_presence_of :name, :if => Proc.new{|f| f.display_name.blank? } # I care about 'f' here as I need it to check something.
...和:
validates_presence_of :secret_sauce, :if => Proc.new{ MyApp::REQUIRE_SECRET_SAUCE } # I don't care about any arguments being passed in.
这似乎是一件小事,但我想它增加了灵活性.
This may seem like a minor thing, but I guess it adds to the flexibility.
这篇关于Rails验证:if => Proc.new还是lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!