Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validation :if => Proc.new or lambda?

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?

like image 723
Xiaotian Guo Avatar asked Jun 03 '11 20:06

Xiaotian Guo


People also ask

How does validation work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

What is the difference between validate and validates in rails?

validates is used for normal validations presence , length , and the like. validate is used for custom validation methods validate_name_starts_with_a , or whatever crazy method you come up with. These methods are clearly useful and help keep data clean. That test fails.

How do I validate in Ruby on Rails?

This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".


1 Answers

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.

like image 168
Jits Avatar answered Oct 04 '22 12:10

Jits