Module: PeriodicCalculable::ClassMethods

Defined in:
app/models/concerns/periodic_calculable.rb

Instance Method Summary collapse

Instance Method Details

#averages_of_periods(options = {}) ⇒ Object


22
23
24
# File 'app/models/concerns/periodic_calculable.rb', line 22

def averages_of_periods(options = {})
  calculate_in_periods(:avg, { name: :average }.merge(options))
end

#calculable(options = {}) ⇒ Object


14
15
16
17
18
19
20
# File 'app/models/concerns/periodic_calculable.rb', line 14

def calculable(options = {})
  for parameter in PeriodicCalculable::PARAMETERS
    if options[parameter]
      send("default_calculable_#{parameter}=", options[parameter])
    end
  end
end

#calculate_in_periods(operation, options = {}) ⇒ Object


34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'app/models/concerns/periodic_calculable.rb', line 34

def calculate_in_periods(operation, options = {})
  column = options[:column] || default_calculable_column
  column = "#{table_name}.#{column}" if column.is_a?(Symbol)
  options[:name] ||= default_calculable_name || column || operation
  options[:period] ||= default_calculable_period
  options[:period] = :doy if options[:period] == :day
  options[:at] ||= default_calculable_at
  options[:at] = "#{table_name}.#{options[:at]}" if options[:at].is_a?(Symbol)
  expr = "EXTRACT(YEAR FROM #{options[:at]})*1000 + EXTRACT(#{options[:period]} FROM #{options[:at]})"
  relation = group(expr).reorder(expr)
  relation = relation.joins(options[:joins]) if options[:joins]
  relation.select("#{expr} AS expr, #{operation}(#{column}) AS #{options[:name]}")
end

#counts_of_periods(options = {}) ⇒ Object


30
31
32
# File 'app/models/concerns/periodic_calculable.rb', line 30

def counts_of_periods(options = {})
  calculate_in_periods(:count, { name: :count }.merge(options))
end

#sums_of_periods(options = {}) ⇒ Object


26
27
28
# File 'app/models/concerns/periodic_calculable.rb', line 26

def sums_of_periods(options = {})
  calculate_in_periods(:sum, { name: :sum }.merge(options))
end