Module: ArAggregateByInterval

Defined in:
lib/ar_aggregate_by_interval.rb,
lib/ar_aggregate_by_interval/utils.rb,
lib/ar_aggregate_by_interval/version.rb,
lib/ar_aggregate_by_interval/query_result.rb,
lib/ar_aggregate_by_interval/query_runner.rb

Overview

POSTGRES AND MYSQL COMPATIBLE ActiveRecordModel.[sum|count]_ examples:

Defined Under Namespace

Modules: Utils Classes: QueryResult, QueryRunner

Constant Summary collapse

VERSION =
'1.2.1'

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ar_aggregate_by_interval.rb', line 11

def method_missing(method_name, *args)
  supported_methods_rgx = /\A(count|sum|avg)_(daily|weekly|monthly)\z/

  aggregate_function, interval = method_name.to_s.scan(supported_methods_rgx).flatten

  return super unless aggregate_function && interval

  hash_args = if args.size == 1 && args.first.is_a?(Hash)
    args.first
  elsif args.size > 1 && !args[0..-2].any?{ |a| a.is_a?(Hash) }
    Utils.args_to_hash(aggregate_function, interval, *args)
  else
    nil
  end

  raise ArgumentError, 'incorrect ArAggregateByInterval arguments' unless hash_args

  # convert strings to symbols
  [:group_by_column, :aggregate_column].each do |col|
    hash_args[col] = hash_args[col].intern if hash_args[col]
  end

  # build query object
  query_runner = QueryRunner.new(self, {
    aggregate_function: aggregate_function,
    interval: interval
  }.merge(hash_args))

  # actually run SQL and return a hash of dates => vals
  date_values_hash = query_runner.run_query

  # takes hash and fills in missing dates
  # this QueryResult object has 2 attributes: values_and_dates, values
  QueryResult.new({
    date_values_hash: date_values_hash,
    from: query_runner.from,
    to: query_runner.to,
    interval: query_runner.interval
  })

end