简体   繁体   English

如何在Ruby on Rails中使用Procs?

[英]How would I use Procs in Ruby on Rails?

There are a few helpers I am using in my project, which I just thought that I could maybe treat as Procs, as they do very specific tasks and can be used by very different components. 我在项目中使用了一些帮助程序,我只是认为我可以将其视为Procs,因为它们执行非常具体的任务并且可以由非常不同的组件使用。

I've used Procs in small Ruby projects, mainly when learning the language, and I thought that this would be a good occasion to put them to use. 我已经在小型Ruby项目中使用了Procs,主要是在学习语言时,我认为这是使用它们的好时机。

My question is, where would I put the Procs in the Rails folder structure? 我的问题是,将Procs放在Rails文件夹结构中的什么位置? Are there any guidelines or reccomdendations for this? 有任何准则或建议吗? Is it considered good practice? 它被认为是好的做法吗?

I am a bit puzzled what the advantage would be of using Procs over using simple methods? 与使用简单方法相比,使用Procs会有什么好处让我有些疑惑? So if you could give some examples, that would be nice. 因此,如果您可以举一些例子,那就太好了。

Anyways: since Procs can be stored in a variable, I would declare a module inside the lib folder, and define the procs as variables, constants, or methods returning the proc. 无论如何:由于Procs可以存储在变量中,因此我将在lib文件夹中声明一个模块,并将proc定义为返回proc的变量,常量或方法。 Something like this 像这样

module ProcContainer

  def proc_1(factor)
    Proc.new { |n| n*factor }
  end

  PROC_2 = Proc.new { |n| 2 * n }

end

which would be used as 用作

gen_proc = ProcContainer.proc_1(6)
result = gen_proc(3)

other_proc = ProcContainer.PROC_2(4)

The advantage of the method is obvious i guess, since it will return a new Proc object every time it is called, while the constant is only evaluated once. 我猜该方法的优点很明显,因为每次调用它都会返回一个新的Proc对象,而常数只被评估一次。

(of course you should change the naming to something more appropriate) (当然,您应该将命名更改为更合适的名称)

Ruby has amazing syntax for blocks, so we tend to favor them over explicitly making procs. Ruby具有惊人的块语法,因此我们倾向于青睐它们而不是显式进行proc。 The downside of blocks is that they need to be executed immediately when the called method yields to them (procs don't have that limitation). 块的缺点是,当被调用的方法屈服时,它们需要立即执行(过程没有此限制)。 That is in place for performance reasons, but you can easily package up a block as a proc, and store it somewhere else for later, or pass it down to another method. 出于性能方面的考虑,这样做是适当的,但是您可以轻松地将一个程序块打包为proc,然后将其存储在其他位置以供以后使用,或者将其传递给其他方法。 So even though you are probably using procs every day, you don't really realize it, because your interface to them is through the block syntax. 因此,即使您可能每天都在使用proc,也并没有真正意识到这一点,因为与它们的接口是通过块语法实现的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM