简体   繁体   中英

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.

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.

My question is, where would I put the Procs in the Rails folder structure? 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? 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. 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.

(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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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