Commit 1456fa0f6dff815317ce11c1c6ef688c20567d9a

Authored by Tres Trantham
1 parent dc20dee6

Add group_calc to enable custom calculations

Showing 2 changed files with 13 additions and 5 deletions   Show diff stats
lib/groupdate/magic.rb
... ... @@ -113,10 +113,18 @@ module Groupdate
113 113 end
114 114  
115 115 count =
116   - begin
117   - 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] } ]
118   - rescue NoMethodError
119   - raise "Be sure to install time zone support - https://github.com/ankane/groupdate#for-mysql"
  116 + if method == :group_calc
  117 + begin
  118 + Hash[relation.select("#{relation.group_values[@group_index]} AS #{@field.to_s}", "#{args[0]} AS calculation").group("#{relation.group_values[@group_index]}").map { |record| [record.send(@field), record.calculation] }]
  119 + rescue
  120 + raise "Could not perform custom calculation. Please check your syntax."
  121 + end
  122 + else
  123 + begin
  124 + 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] } ]
  125 + rescue NoMethodError
  126 + raise "Be sure to install time zone support - https://github.com/ankane/groupdate#for-mysql"
  127 + end
120 128 end
121 129  
122 130 series(count, 0, multiple_groups, reverse)
... ...
lib/groupdate/series.rb
... ... @@ -10,7 +10,7 @@ module Groupdate
10 10 # clone to prevent modifying original variables
11 11 def method_missing(method, *args, &block)
12 12 # https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation/calculations.rb
13   - if ActiveRecord::Calculations.method_defined?(method)
  13 + if ActiveRecord::Calculations.method_defined?(method) || method == :group_calc
14 14 magic.perform(relation, method, *args, &block)
15 15 elsif @relation.respond_to?(method)
16 16 Groupdate::Series.new(magic, relation.send(method, *args, &block))
... ...