I understand the concept of a proc but sometime I see code like this (take from rails guide for validation http://guides.rubyonrails.org/active_record_validations_callbacks.html#using-if-and-unless-with-a-proc):
class Order < ActiveRecord::Base
before_save :normalize_card_number,
:if => Proc.new { |order| order.paid_with_card? }
end
it seems this could be more simply written as:
class Order < ActiveRecord::Base
before_save :normalize_card_number, :if => :paid_with_card?
end
What am I not getting about the advantage of using a Proc here?
thx in advance
In simple cases they are equivalent, but procs allow far more versatility without requiring a method to be defined simply for a validation if check.
Imagine this:
before_save :nuke, :if => Proc.new { |model| !model.nuked? && model.nukable? && model.region.nukable? }
You can always write that check in an instance method and reference it with a symbol, but for cases where the specific logic is only in the :if, it is valid to keep it in a proc.