Sha256: fe08da2f6700652bf094a5d5486e3503dc150d2c149868a9e970feafd416c2e8

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

require 'delegate'

module Mongoid
  module Report

    class Collection < SimpleDelegator
      def initialize(context, rows, fields, columns)
        @context = context
        @rows    = rows
        @fields  = fields
        @columns = columns

        # 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)
      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

          @columns.each do |name, function|
            summary[name] = function.call(@context, row)
          end

          summary
        end.with_indifferent_access
      end

      private

      def compile_dynamic_fields(rows, columns)
        rows.map do |row|
          @columns.each do |name, function|
            row[name] = function.call(@context, row)
          end

          row.with_indifferent_access
        end
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongoid-report-0.1.6 lib/mongoid/report/collection.rb