lib/mongoid/report/collection.rb in mongoid-report-0.1.6 vs lib/mongoid/report/collection.rb in mongoid-report-0.1.7
- old
+ new
@@ -7,44 +7,47 @@
def initialize(context, rows, fields, columns)
@context = context
@rows = rows
@fields = fields
@columns = columns
+ @rows = compile_rows
- # Apply dyncamic columns in context of row and apply indifferent access
- # for the rows.
- rows = compile_dynamic_fields(rows, columns)
-
# Collection should behave like Array using delegator method.
- super(rows)
+ super(@rows)
end
- def summary
- @summary ||= reduce(Hash.new{|h, k| h[k] = 0}) do |summary, row|
- @fields.each do |field|
- next if @columns.has_key?(field.to_s)
- summary[field] += row[field.to_s]
- end
-
+ def compile_rows
+ @rows.map do |row|
@columns.each do |name, function|
- summary[name] = function.call(@context, row)
+ next unless @fields.include?(name)
+ row[name] = function.call(@context, row, { summary: false })
end
- summary
- end.with_indifferent_access
+ row
+ end
end
- private
+ def summary
+ @summary ||= reduce(Hash.new{|h, k| h[k] = 0}) do |summary, row|
+ # Find summary for aggregated rows
+ @fields.each do |field|
+ # Don't apply for dynamic calculated columns lets wait until we get
+ # all summaried mongo columns and then apply dynamic columns
+ # calculations.
+ next if @columns.has_key?(field)
+ summary[field] += row[field]
+ end
- def compile_dynamic_fields(rows, columns)
- rows.map do |row|
+ # Apply dynamic columns for summarized row
@columns.each do |name, function|
- row[name] = function.call(@context, row)
+ next unless @fields.include?(name)
+ summary[name] = function.call(@context, row, { summary: true })
end
- row.with_indifferent_access
+ summary
end
end
+
end
end
end