I don’t know why Proc will be used here - do not get something simple

I understand the concept of proc, but someday I see this code (take from the rails manual for checking 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 like it would be easier to write like:

 class Order < ActiveRecord::Base before_save :normalize_card_number, :if => :paid_with_card? end 

What I don’t understand about the benefits of using Proc here?

thanks in advance

+4
source share
2 answers

In simple cases, they are equivalent, but procs provide much more flexibility, without requiring the method to be defined simply for verification, if verification.

Imagine the following:

 before_save :nuke, :if => Proc.new { |model| !model.nuked? && model.nukable? && model.region.nukable? } 

You can always write this check in the instance method and refer to it with a symbol, but for cases where the specific logic is only in: if, it really should contain it in proc.

+5
source

They are equivalent if the receiver of the method is the object being checked. This is not quite the way ActiveModel validators work, but the concept is similar:

Calling to_proc on a character :sym gives you the functional equivalent β†’ β†’ (x) {x.sym} - the character is sent as a message to the proc argument. Calling to_proc in proc just returns itself, so you can pass either a character or proc to a method and guarantee proc:

 def return_a_proc(symbol_or_proc) symbol_or_proc.to_proc end 

In cases where the model instance is not a receiver, for example. the validation method takes the model as an argument or, as in Daniel Evans's example, you need to explicitly build proc to indicate what should be done with the proc argument.

+1
source

All Articles