Issue
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?
Solution
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.
Answered By - Aleksei Matiushkin Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.