Class: SnowmanIO::App

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Document, Mongoid::Timestamps, Concerns::Tokenable
Defined in:
lib/snowman-io/models/app.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Concerns::Tokenable

#generate_token

Class Method Details

.time(name, &block) ⇒ Object



18
19
20
21
22
23
# File 'lib/snowman-io/models/app.rb', line 18

def self.time(name, &block)
  app = App.where(system: true).first
  start = Time.now.to_f
  yield
  app.register_metric_value(name, "time", Time.now.to_f - start, Time.now)
end

.value(name, v, at = Time.now) ⇒ Object



25
26
27
28
# File 'lib/snowman-io/models/app.rb', line 25

def self.value(name, v, at = Time.now)
  app = App.where(system: true).first
  app.register_metric_value(name, "amount", v, at)
end

Instance Method Details

#as_json(options = {}) ⇒ Object



30
31
32
33
34
35
# File 'lib/snowman-io/models/app.rb', line 30

def as_json(options = {})
  super(options.merge(methods: [:datapoints, :metric_ids])).tap do |o|
    o["id"] = o.delete("_id").to_s
    o["metric_ids"] = o["metric_ids"].map(&:to_s)
  end
end

#daily_metrics(at) ⇒ Object

Returns amount of datapoints for ‘at` and day before



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/snowman-io/models/app.rb', line 38

def daily_metrics(at)
  json = {}

  today = at.beginning_of_day
  yesterday = at.beginning_of_day - 1.day
  json["today"] = {"at" => today.strftime("%Y-%m-%d"), "count" => 0}
  json["yesterday"] = {"at" => yesterday.strftime("%Y-%m-%d"), "count" => 0}
  json["total"] = {"count" => 0}

  # TODO: impl it more performable
  metrics.each do |metric|
    if aggr = metric.aggregations.where(precision: "daily", at: today).first
      json["today"]["count"] += aggr.count.to_i
    end

    if aggr = metric.aggregations.where(precision: "daily", at: yesterday).first
      json["yesterday"]["count"] += aggr.count.to_i
    end

    json["total"]["count"] += metric.aggregations.where(precision: "daily").sum(:count).to_i
  end

  json
end

#datapointsObject



70
71
72
# File 'lib/snowman-io/models/app.rb', line 70

def datapoints
  daily_metrics(Time.now)
end

#register_metric_value(name, kind, value, at = Time.now) ⇒ Object



63
64
65
66
67
68
# File 'lib/snowman-io/models/app.rb', line 63

def register_metric_value(name, kind, value, at = Time.now)
  metric = metrics.where(name: name, kind: kind).first_or_create!
  metric.update_attributes!(last_value: value, last_value_updated_at: Time.now)
  metric.data_points.create!(at: at, value: value)
  touch
end