Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为什么要使用Proc.new在Rails回调中调用方法?_Ruby On Rails_Ruby_Proc Object - Fatal编程技术网

Ruby on rails 为什么要使用Proc.new在Rails回调中调用方法?

Ruby on rails 为什么要使用Proc.new在Rails回调中调用方法?,ruby-on-rails,ruby,proc-object,Ruby On Rails,Ruby,Proc Object,在RoR的所有教程中,我都看到过这样的例子:程序员选择使用Proc.new,而这似乎是不必要的,而且相当不吸引人 例如,下面是放置在模型中的的的回调,一个使用Proc.new,另一个可能执行相同的操作: class Order < ActiveRecord::Base before_save :normalize_card_number, :if => Proc.new { |order| order.paid_with_card? } end class

在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.new{| order | order.paid_with_card?}
结束
类顺序“使用卡支付?”
结束
那么有什么区别呢?为什么要使用Proc?他们不是都称之为“用信用卡支付”方法吗


提前感谢

我想说的是,在旧版本的Rails中,我们就是这样做的,有人添加了一个功能,您可以通过该功能将字符串作为当前模型上的实例方法进行计算


在简单的场景中,它使旧样式变得多余,但允许对更复杂的“if”语句使用Proc,而仅在当前实例上使用方法是不可能实现的。

在上面的示例中,对条件方法使用符号可能是最佳选择

class Order < ActiveRecord::Base
  before_save :normalize_card_number, :if => :paid_with_card?
end
类顺序:用卡支付?
结束
string选项使用eval来计算字符串中的Ruby代码。所以就我个人而言,我更喜欢在调用方法时使用符号,或者在编写短内联条件时使用Proc

根据:

使用Proc对象可以编写内联条件,而不是单独的方法。此选项最适合单行程序

我认为使用Proc可以更好地用以下方式来说明:

class Order < ActiveRecord::Base
  before_save :normalize_card_number,
    :if => Proc.new { |order| order.payment_type == "card" }
end
类顺序Proc.new{| order | order.payment_type==“card”}
结束

这样可能就不需要使用带卡付费了吗?方法。

是的,最好不要将rails模型与paid_with_card之类的方法混为一谈?我认为:如果事情表明有大量配置选项会自动包含并从另一个上下文中重用。有一种默认的处理方法:if=>string、proc等来配置这样的选项,可能还有:除非也可以。