Sha256: 6af2fda37ee3238d6dd6802217a4182caa5fe1331d67be5c3ea6371dce764533

Contents?: true

Size: 1.01 KB

Versions: 1

Compression:

Stored size: 1.01 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|
            summary[field] += row[field.to_s]
          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.5 lib/mongoid/report/collection.rb