Class: ModelsStats::Statistics

Inherits:
Object
  • Object
show all
Defined in:
lib/models_stats/statistics.rb

Constant Summary collapse

DEFAULT_SELECT_STATEMENT =
"COUNT(id) AS count"

Class Method Summary collapse

Class Method Details

.default_group_by_values_map(group_by, model) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/models_stats/statistics.rb', line 5

def self.default_group_by_values_map(group_by, model)
  model_klass = model.to_s.constantize
  if model_klass.respond_to?(:state_machine)
    state_machine_states = model_klass.state_machine.states
    state_machine_defined = !state_machine_states.first.name.nil?

    if state_machine_defined #&& value_numeric?(group_by)
      Hash[model.to_s.constantize.state_machine.states.map{|state| [state.value, state.name]}]
    else
      {}
    end
  else
    {}
  end
end

.for_period(stat_name, period = 1.month) ⇒ Object



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
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/models_stats/statistics.rb', line 25

def self.for_period(stat_name, period = 1.month)
  model_statistics = []

  period.ago.to_date.upto(Date.yesterday) do |date|
    stat = read(stat_name, date)
    next if stat.empty?

    model_statistics << [date, stat]
  end

  all_keys = []
  stat = []

  model_statistics.each do |stat|
    stat[1].each do |key, count|
      models_count = count.to_i
      if models_count > 0
        all_keys << key unless all_keys.include?(key)
      end
    end
  end

  all_keys.each do |key|
    values = []
    model_statistics.each do |stat|
      date = stat[0]
      stat[1].each do |k, count|
        if k == key
          values << {date: date.to_s, value: count.to_i}
        end
      end
    end

    stat << values
  end

  return all_keys, stat
end

.value_numeric?(value) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/models_stats/statistics.rb', line 21

def self.value_numeric?(value)
  !value.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/).nil?
end

.write_day(stat, stat_alias, date) ⇒ Object



64
65
66
67
68
# File 'lib/models_stats/statistics.rb', line 64

def self.write_day(stat, stat_alias, date)
  full_key = full_key(stat_alias, date)
  hash = Redis::HashKey.new(full_key, self.redis_connection)
  hash.bulk_set(stat)
end