You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The text was updated successfully, but these errors were encountered:
ydakuka
changed the title
Cop idea: prefer ActiveRecord::Calculations some methods over Enumerable some methods
Cop idea: prefer .maximum and .minimum over .pluck & .max or .minDec 14, 2023
@ydakuka
I've reviewed the suggested cop idea, and I think it's a valuable addition. Utilizing ActiveRecord::Calculations methods like maximum and minimum not only enhances code readability but also brings potential performance improvements.
The proposed solution, which suggests using ActiveRecord::Calculations methods (maximum and minimum) instead of pluck followed by min or max, is a good idea. Here are a few reasons why this solution might be beneficial:
Performance Improvement:
ActiveRecord::Calculations methods are optimized for database-level calculations, which can result in more efficient queries.
Using Loan.minimum(:amount) or Loan.maximum(:amount) often translates to a single SQL query, while Loan.pluck(:amount).min or Loan.pluck(:amount).max involves fetching all records and performing the calculation in Ruby.
Readability:
The intent of the code becomes clearer when using minimum and maximum directly, making it easier for other developers (or even yourself) to understand the purpose of the code.
Code Conciseness:
The alternative code (Loan.pluck(:amount).min or Loan.pluck(:amount).max) is longer and involves multiple method calls. Using minimum and maximum directly makes the code more concise.
Consistency:
Favoring ActiveRecord::Calculations methods promotes consistency in your codebase. Developers working on the project will use a standardized approach for such queries.
Compatibility:
As Rails evolves, methods like pluck followed by min or max might become less favorable or less efficient. Using the recommended ActiveRecord::Calculations methods ensures compatibility with future Rails versions.
I support the idea of encouraging developers to adopt this pattern, and I believe it aligns well with the practices mentioned in the provided references.
Looking forward to hearing more thoughts from the community on this proposed cop!
Describe the solution you'd like
https://www.fastruby.io/blog/rails/performance/writing-fast-rails-part-2 (rails 6.0)
https://blog.saeloun.com/2021/03/17/rails-enumerable-maximum-and-minimum/ (rails 7.0)
The text was updated successfully, but these errors were encountered: