Class: ExpressAnalytics::DailyStatistic

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
ActionView::Helpers::NumberHelper
Defined in:
app/models/express_analytics/daily_statistic.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

._arrayify(date_or_date_range) ⇒ Object



47
48
49
50
51
52
53
54
# File 'app/models/express_analytics/daily_statistic.rb', line 47

def self._arrayify(date_or_date_range)
  if date_or_date_range.present? &&
     date_or_date_range.kind_of?(Range)
    date_or_date_range.to_a
  else
    [date_or_date_range].flatten.compact
  end
end

._calculate_for_date!(date) ⇒ Object



56
57
58
59
60
61
# File 'app/models/express_analytics/daily_statistic.rb', line 56

def self._calculate_for_date!(date)
  stat = find_by_calculated_for(date.to_date) || new(calculated_for: date.to_date)
  stat.calculate!
  stat.save
  stat
end

.aggregate_for(range) ⇒ Object



36
37
38
39
# File 'app/models/express_analytics/daily_statistic.rb', line 36

def self.aggregate_for(range)
  aggregate_record = where(calculated_for: range).select("#{aggregation_operation.to_s.upcase}(value) AS value").order(nil).first
  aggregate_record.value
end

.aggregation_operationObject



41
42
43
# File 'app/models/express_analytics/daily_statistic.rb', line 41

def self.aggregation_operation
  :sum
end

.all_statisticsObject



5
6
7
8
9
10
11
12
# File 'app/models/express_analytics/daily_statistic.rb', line 5

def self.all_statistics
  Dir.glob(File.join(Rails.root, 'app', 'statistics', '*.rb')).map do |statistic|
    file_name = File.basename(statistic).gsub('.rb', '')
    class_name = file_name.classify
    class_name = class_name.pluralize if file_name.match(/s$/)
    class_name.constantize
  end
end

.calculate(&block) ⇒ Object



18
19
20
# File 'app/models/express_analytics/daily_statistic.rb', line 18

def self.calculate(&block)
  define_method(calculate_method_name, &block)
end

.calculate!(date_or_date_range = nil) ⇒ Object



22
23
24
25
26
# File 'app/models/express_analytics/daily_statistic.rb', line 22

def self.calculate!(date_or_date_range = nil)
  _arrayify(date_or_date_range||Date.today).each do |date|
    _calculate_for_date!(date)
  end
end

.calculate_all!(date = nil) ⇒ Object



14
15
16
# File 'app/models/express_analytics/daily_statistic.rb', line 14

def self.calculate_all!(date=nil)
  all_statistics.each { |stat| stat.calculate!(date) }
end

.calculate_method_nameObject



63
64
65
# File 'app/models/express_analytics/daily_statistic.rb', line 63

def self.calculate_method_name
  "calculate_#{self.class.to_s.underscore}!".to_sym
end

Instance Method Details

#calculate!Object



28
29
30
# File 'app/models/express_analytics/daily_statistic.rb', line 28

def calculate!
  self.value = send(self.class.calculate_method_name, calculated_for)
end

#value_formattedObject



32
33
34
# File 'app/models/express_analytics/daily_statistic.rb', line 32

def value_formatted
  self.value
end