PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 11, 2022

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

 November 11, 2022     lambda, proc, ruby, ruby-on-rails, validation     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing