Mittwoch, 20. Februar 2013

The quick Proc

In the previous post Yield your block in Ruby I described how to code a block and its short cut "yield". You may have noticed that another kind of closure, the Proc. The goal behind is the same as the already explained block. But you will get into the situation to save a block for later dynamic use. I used a Proc the first time in my very first Ruby On Rails project.
That's why I also explain the Proc in a Rails example now.
Let's assume a model Machine:
class Machine
  attr_accessor :in_progress
  attr_accessible :name
  validates :name, :presence => true, :unless => Proc.new { |machine| machine.in_progress.blank? } 
end
having the accessor methods generated through "attr_accessor". Furthermore there is the model attribute "name" for the machine name. I want the machine validate its name for presence only in the case of the machine was already started.
That's why there is the third call "validates". And it is only called, when the :unless key contains a false. Since the validation call is dynamic, there is a Proc assigned. It executes its code not before the validation call and can return true or false depending on the value of the instance variable @in_progress.
I agree, the logic of the Proc also could be put into an instance method, say "in_progress?" (as it would be generated by Rails, if it was a model attribute).
But why should I? I only need the logic once and this way it is more readable, because it is located next to the key.
So when do I use a Proc?
I do, when some logic should be called dynamically and not be put into a method for some reasons.

Supported by Ruby 1.9.3, RubyOnRails 3.1

Keine Kommentare:

Kommentar veröffentlichen