Ruby-on-rails Rails 验证:if => Proc.new 还是 lambda?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6232099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:18:52  来源:igfitidea点击:

Rails validation :if => Proc.new or lambda?

ruby-on-railslambda

提问by Xiaotian Guo

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

我发现在所有示例(包括 rails 文档)中,我看到的 :if 验证方法选项使用 Proc.new 而不是 lambda,例如

class Foo < ActiveRecord::Base
  validates_presence_of :name, :if => Proc.new{|f| .... } # why not lambda here?
end

is there any reason for this? As far as I know, lambda

有什么原因吗?据我所知,拉姆达

  1. Is more strict with arguments.
  2. Also return statement in lambda block returns from the block, not from calling function.
  1. 对参数更严格。
  2. lambda 块中的 return 语句也从块中返回,而不是从调用函数中返回。

Both seems to be desirable behavior for :if option mentioned above, is there anything I am missing?

两者似乎都是理想的行为:如果上面提到的选项,有什么我遗漏的吗?

回答by Jits

Both seems to be desirable behavior for :if option mentioned above, is there anything I am missing?

两者似乎都是理想的行为:如果上面提到的选项,有什么我遗漏的吗?

I'm guessing that:

我猜是:

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:

允许 Procs 更可取,因为它们不关心参数的数量。所以我可以轻松地编写以下任何内容:

validates_presence_of :name, :if => Proc.new{|f| f.display_name.blank? }    # I care about 'f' here as I need it to check something.

... and:

... 和:

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.

这似乎是一件小事,但我想它增加了灵活性。