-
Notifications
You must be signed in to change notification settings - Fork 21.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Make average compatible across ruby versions #34858
Make average compatible across ruby versions #34858
Conversation
This reverts commit 89b4612.
@@ -401,11 +401,17 @@ def type_cast_calculated_value(value, type, operation = nil) | |||
case operation | |||
when "count" then value.to_i | |||
when "sum" then type.deserialize(value || 0) | |||
when "average" then value.respond_to?(:to_d) ? value.to_d : value | |||
when "average" then cast_average(value) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just enough value&.respond_to?(:to_d) ? value.to_d : value
or value && value.respond_to?(:to_d) ? value.to_d : value
.
when "average" then cast_average(value) | |
when "average" then value && value.respond_to?(:to_d) ? value.to_d : value |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the suggestion @kamipo change applied. 🙏
Since Ruby 2.6.0 NilClass#to_d is returning `BigDecimal` 0.0, this breaks `average` compatibility with prior Ruby versions. This patch makes `average` return `nil` in all Ruby versions when there are no rows.
r? @kamipo |
Returning The reason that I pasted the all operation cases in #34601 (comment) was for rails/activerecord/lib/active_record/relation/calculations.rb Lines 400 to 405 in e7717ec
Databases also returns I believe that is historical reason, but it is a good timing to discuss the odd inconsistency for no records |
I think it makes sense to |
I don't know I get your point, you means that the difference (1) and (3) is less important than the difference (2) and (4), right?
|
Yes. I can't think in a case where I need to know the sum of all records is 0 because there are no records or because all records are 0. |
I see, I agree that the difference is less important. |
…ccross-ruby-versions Make average compatible across ruby versions
Ruby 2.6 added `to_d` to BigDecimal and it was causing some tests to fail because of that. See rails/rails#34858
Summary
Since Ruby 2.6.0
NilClass#to_d
is returningBigDecimal
0.0. This breaksaverage
compatibility with prior Ruby versions. This patch makesaverage
returnnil
in all Ruby versions when there are no rows.Other Information
Reverts #34601
Fixes #34850
r? @rafaelfranca