Commit 82815bbba233e6282f3cc9a578353af4aab5b549
1 parent
dc6467c2
Exists in
group_calc
Test group_calc with multiple groups
Showing
2 changed files
with
17 additions
and
5 deletions
Show diff stats
lib/groupdate/magic.rb
... | ... | @@ -132,11 +132,13 @@ module Groupdate |
132 | 132 | |
133 | 133 | count = |
134 | 134 | begin |
135 | - if method == :group_calc | |
136 | - Hash[ relation.select("#{relation.group_values[@group_index]} AS #{@field}", "#{args[0]} AS calculation").group("#{relation.group_values[@group_index]}").map{|record| [record.send(@field), record.calculation] } ] | |
137 | - else | |
138 | - Hash[ relation.send(method, *args, &block).map{|k, v| [multiple_groups ? k[0...@group_index] + [cast_method.call(k[@group_index])] + k[(@group_index + 1)..-1] : cast_method.call(k), v] } ] | |
139 | - end | |
135 | + calculation = | |
136 | + if method == :group_calc | |
137 | + Hash[ relation.group("#{relation.group_values[@group_index]}").pluck("#{relation.group_values[@group_index]} AS #{@field}, #{args[0]} AS calculation") ] | |
138 | + else | |
139 | + relation.send(method, *args, &block) | |
140 | + end | |
141 | + Hash[ calculation.map{|k, v| [multiple_groups ? k[0...@group_index] + [cast_method.call(k[@group_index])] + k[(@group_index + 1)..-1] : cast_method.call(k), v] } ] | |
140 | 142 | rescue NoMethodError |
141 | 143 | raise "Be sure to install time zone support - https://github.com/ankane/groupdate#for-mysql" |
142 | 144 | end | ... | ... |
test/test_helper.rb
... | ... | @@ -789,6 +789,16 @@ module TestGroupdate |
789 | 789 | assert_equal 15, User.group_by_day(:created_at).group_calc("SUM(score) * 1.0 / COUNT(*)")[utc.parse("2014-05-01 00:00:00 UTC")] |
790 | 790 | end |
791 | 791 | |
792 | + def test_group_calc_multiple_groups | |
793 | + create_user "2014-05-01 00:00:00 UTC", 10 | |
794 | + create_user "2014-05-01 00:00:00 UTC", 20 | |
795 | + expected = { | |
796 | + [10, utc.parse("2014-05-01 00:00:00 UTC")] => 10, | |
797 | + [20, utc.parse("2014-05-01 00:00:00 UTC")] => 20 | |
798 | + } | |
799 | + assert_equal expected, User.group(:score).group_by_day(:created_at).group_calc("SUM(score) * 1.0 / COUNT(*)") | |
800 | + end | |
801 | + | |
792 | 802 | # helpers |
793 | 803 | |
794 | 804 | def assert_format(method, expected, format, options = {}) | ... | ... |