Class: ConservationGuardian::Profiler

Inherits:
Object
  • Object
show all
Defined in:
lib/conservation_guardian/profiler.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(budget) ⇒ Profiler

Returns a new instance of Profiler.



7
8
9
10
# File 'lib/conservation_guardian/profiler.rb', line 7

def initialize(budget)
  @budget  = budget
  @samples = []
end

Instance Attribute Details

#budgetObject (readonly)

Returns the value of attribute budget.



5
6
7
# File 'lib/conservation_guardian/profiler.rb', line 5

def budget
  @budget
end

#samplesObject (readonly)

Returns the value of attribute samples.



5
6
7
# File 'lib/conservation_guardian/profiler.rb', line 5

def samples
  @samples
end

Instance Method Details

#all_statsObject



40
41
42
43
44
# File 'lib/conservation_guardian/profiler.rb', line 40

def all_stats
  @samples.map { |s| s[:category] }.uniq.each_with_object({}) do |cat, h|
    h[cat] = stats_for(cat)
  end
end

#clear!Object



50
51
52
# File 'lib/conservation_guardian/profiler.rb', line 50

def clear!
  @samples.clear
end

#ingest(samples) ⇒ Object

samples: Array of { category:, value:, label: } or pass a single sample at a time



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/conservation_guardian/profiler.rb', line 14

def ingest(samples)
  samples = [samples] if samples.is_a?(Hash)
  samples.each do |s|
    @samples << {
      category: s[:category].to_sym,
      value:    s[:value].to_f,
      label:    s[:label].to_s,
      timestamp: Time.now
    }
  end
end

#over_budget_samplesObject



46
47
48
# File 'lib/conservation_guardian/profiler.rb', line 46

def over_budget_samples
  @samples.select { |s| @budget.exceeded?(s[:category], s[:value]) }
end

#stats_for(category) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/conservation_guardian/profiler.rb', line 26

def stats_for(category)
  cat = category.to_sym
  vals = @samples.select { |s| s[:category] == cat }.map { |s| s[:value] }
  return nil if vals.empty?

  {
    count: vals.size,
    min:   vals.min,
    max:   vals.max,
    sum:   vals.sum,
    avg:   vals.sum / vals.size
  }
end