为什么使用 Proc.new 来调用 Rails 回调中的方法?
在所有 RoR 教程中,我看到编码员选择使用 Proc.new 的实例,但看起来它既不必要又没有吸引力。
例如,这里是放置在模型中的回调,一个使用 Proc.new,另一个可能做同样的事情:
class Order < ActiveRecord::Base
before_save :normalize_card_number,
:if => Proc.new { |order| order.paid_with_card? }
end
class Order < ActiveRecord::Base
before_save :normalize_card_number, :if => "paid_with_card?"
end
那么有什么区别呢?为什么要使用Proc?他们不是都叫“paid_with_card”吗?方法?
提前致谢
in all the tutorials for RoR I see instances where the coder chose to use Proc.new when seemingly it is both unnecessary and rather unattractive.
Example, here is a callback for placed in a model, one using Proc.new the other presumably doing the same thing:
class Order < ActiveRecord::Base
before_save :normalize_card_number,
:if => Proc.new { |order| order.paid_with_card? }
end
class Order < ActiveRecord::Base
before_save :normalize_card_number, :if => "paid_with_card?"
end
So what's the difference? Why use the Proc? Don't they both call the "paid_with_card?" method?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在上面的示例中,使用符号作为条件方法可能是最佳选择。
字符串选项使用 eval 来计算字符串中的 Ruby 代码。因此,就我个人而言,如果调用方法或编写简短的内联条件,我更愿意使用符号。
根据 RailsGuides 文档:
我认为使用 Proc 可能会更好地说明这种方式:
这可能会消除对paid_with_card的需要?方法。
In the example above, using a symbol for the conditional method would probably be the best choice.
The string option uses eval to evaluate the Ruby code in the string. So personally, I would prefer to use a symbol if calling a method or a Proc if writing a short inline condition.
Per the RailsGuides documentation:
I think using a Proc might be better illustrated this way:
This would possibly eliminate the need for the paid_with_card? method.
我想说的是,在旧版本的 Rails 中,我们就是这样做的,有人添加了这样的功能,您可以传递一个字符串作为当前模型上的实例方法进行评估。
在简单的场景中,它使旧的样式变得多余,但允许使用 Proc 来执行更复杂的“if”语句,而仅在当前实例上使用方法是不可能实现的。
I'd say it was the case that in older versions of Rails that's how we used to do things, and someone added the feature whereby you could pass a string to be evaluated as an instance method on the current model.
In simple scenarios it makes the older style redundant, but allows for the use of a Proc for more complex 'if' statements which would be impossible to achieve using a method on only the current instance.