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:
return
from a proc would exit the method in which it is called.Lambda:
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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With