Module: Saulabs::Reportable::ClassMethods

Defined in:
lib/saulabs/reportable.rb

Instance Method Summary collapse

Instance Method Details

#reportable(name, options = {}) ⇒ Object

Generates a report on a model. That report can then be executed via the new method <name>_report (see documentation of Report#run).

Examples:

Declaring reports on a model


class User < ActiveRecord::Base
  reportable :registrations, :aggregation => :count
  reportable :activations,   :aggregation => :count, :date_column => :activated_at
  reportable :total_users,   :cumulate => true
  reportable :rake,          :aggregation => :sum,   :value_column => :profile_visits
end

Parameters:

  • name (String)

    the name of the report, also defines the name of the generated report method (+<name>_report+)

  • options (Hash) (defaults to: {})

    the options to generate the reports with

Options Hash (options):

  • :date_column (Symbol) — default: created_at

    the name of the date column over that the records are aggregated

  • :value_column (String, Symbol) — default: :id

    the name of the column that holds the values to aggregate when using a calculation aggregation like :sum

  • :aggregation (Symbol) — default: :count

    the aggregation to use (one of :count, :sum, :minimum, :maximum or :average); when using anything other than :count, :value_column must also be specified

  • :grouping (Symbol) — default: :day

    the period records are grouped in (:hour, :day, :week, :month); Beware that reportable treats weeks as starting on monday!

  • :limit (Fixnum) — default: 100

    the number of reporting periods to get (see :grouping)

  • :conditions (Hash) — default: {}

    conditions like in ActiveRecord::Base#find; only records that match these conditions are reported;

  • :live_data (Boolean) — default: false

    specifies whether data for the current reporting period is to be read; if :live_data is true, you will experience a performance hit since the request cannot be satisfied from the cache alone

  • :end_date (DateTime, Boolean) — default: false

    when specified, the report will only include data for the :limit reporting periods until this date.



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/saulabs/reportable.rb', line 45

def reportable(name, options = {})
  (class << self; self; end).instance_eval do
    define_method "#{name.to_s}_report".to_sym do |*args|
      if options.delete(:cumulate)
        report = Saulabs::Reportable::CumulatedReport.new(self, name, options)
      else
        report = Saulabs::Reportable::Report.new(self, name, options)
      end
      raise ArgumentError.new unless args.length == 0 || (args.length == 1 && args[0].is_a?(Hash))
      report.run(args.length == 0 ? {} : args[0])
    end
  end
end