Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better to use in Rails model validation: Proc or lambda? [closed]

I know the difference between proc and lambda. Which is better to use in Rails model validation according to the guidelines: Proc or lambda?

Proc:

  • Similar behavior as block.
  • Can be stored in a variable and be moved around.
  • No issue with the number of arguments.
  • return from a proc would exit the method in which it is called.

Lambda:

  • Same as Proc, but closer to a method.
  • Strict regarding the arguments it gets and it needs.
  • return from a lambda would exit the lambda, and the method in which it is called would continue executing.

But I haven't seen a validation in which it makes a difference:

validates :name, present: true, if: -> { assotiation.present? }
validates :name, present: true, if: proc { |c| c.assotiation.present? }

I checked rubocop and didn't find any bits of advice about it. Do you know which is better in the opinion of ruby/rails style guide, rubocop or something else?

like image 319
dluhhbiu Avatar asked Dec 24 '22 00:12

dluhhbiu


2 Answers

The only difference I can think of would be a possibility to use early returns from λs. That said, the former would happily validate, while the latter would raise LocalJumpError:

validates :name, present: true,
  if: -> { return false unless assotiation; assotiation.present? }
validates :name, present: true,
  if: proc { return false unless assotiation; assotiation.present? }

Also, I use the following rule of thumb: strict is better than wide-open. So unless it’s absolutely definite that you need a proc, λ is the better tool to use everywhere.

like image 140
Aleksei Matiushkin Avatar answered Mar 08 '23 23:03

Aleksei Matiushkin


Doesn't matter on the real projects :)

for example on my projects I'm doing like this:

validates :source, presence: true, if: :validated_source_field?

(using method)

like image 45
Igor Kasyanchuk Avatar answered Mar 08 '23 23:03

Igor Kasyanchuk