36

I have found that in all examples (include rails documentation) that I have seen for the :if option of validation methods uses Proc.new instead of lambda, for example

class Foo < ActiveRecord::Base
  validates_presence_of :name, :if => Proc.new{|f| .... } # why not lambda here?
end

is there any reason for this? As far as I know, lambda

  1. Is more strict with arguments.
  2. Also return statement in lambda block returns from the block, not from calling function.

Both seems to be desirable behavior for :if option mentioned above, is there anything I am missing?

1 Answer 1

41

Both seems to be desirable behavior for :if option mentioned above, is there anything I am missing?

I'm guessing that:

It's more desirable to allow Procs as they don't care about the number of arguments. So I could easily write any of the below:

validates_presence_of :name, :if => Proc.new{|f| f.display_name.blank? }    # I care about 'f' here as I need it to check something.

... and:

validates_presence_of :secret_sauce, :if => Proc.new{ MyApp::REQUIRE_SECRET_SAUCE }    # I don't care about any arguments being passed in.

This may seem like a minor thing, but I guess it adds to the flexibility.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Jits, I think it's pretty rare that I'd use a :if option without the model instance, in that case I can still just put |dummy| there. So I'd go with lambda, but you explanation makes sense.
But do we really need to pass the instance as an argument? If I understand correctly, code in the block (either in Proc.new or lambda) will just be evaulated when needed and it is possible to write something like this: has_many :associated_objects before_save :do_something, if: -> { associated_objects.empty? } Notice that I skipped argument { |instance| instance.associated_... }
FYI, Rubocop wants me to use just proc instead of Proc.new now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.