Class: RailsPerformance::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_performance/utils.rb

Class Method Summary collapse

Class Method Details

.cache_key(now = Date.today) ⇒ Object

date key in redis store



4
5
6
# File 'lib/rails_performance/utils.rb', line 4

def self.cache_key(now = Date.today)
  "date-#{now}"
end

.daysObject



35
36
37
# File 'lib/rails_performance/utils.rb', line 35

def self.days
  (RailsPerformance.duration / 1.day) + 1
end

.fetch_from_redis(query) ⇒ Object



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

def self.fetch_from_redis(query)
  RailsPerformance.log "\n\n   [REDIS QUERY]   -->   #{query}\n\n"

  keys = RailsPerformance.redis.keys(query)
  return [] if keys.blank?
  values = RailsPerformance.redis.mget(keys)

  RailsPerformance.log "\n\n   [FOUND]   -->   #{values.size}\n\n"

  [keys, values]
end

.field_key(now = Time.current) ⇒ Object

write to current slot time - date -minute



10
11
12
# File 'lib/rails_performance/utils.rb', line 10

def self.field_key(now = Time.current)
  now.strftime("%H:%M")
end

.median(array) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rails_performance/utils.rb', line 39

def self.median(array)
  sorted = array.sort
  size = sorted.size
  center = size / 2

  if size == 0
    nil
  elsif size.even?
    (sorted[center - 1] + sorted[center]) / 2.0
  else
    sorted[center]
  end
end

.percentile(values, percentile) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/rails_performance/utils.rb', line 53

def self.percentile(values, percentile)
  return nil if values.empty?

  sorted = values.sort
  rank = (percentile.to_f / 100) * (sorted.size - 1)

  lower = sorted[rank.floor]
  upper = sorted[rank.ceil]
  lower + (upper - lower) * (rank - rank.floor)
end

.save_to_redis(key, value, expire = RailsPerformance.duration.to_i) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/rails_performance/utils.rb', line 26

def self.save_to_redis(key, value, expire = RailsPerformance.duration.to_i)
  # TODO think here if add return
  # return if value.empty?

  RailsPerformance.log "  [SAVE]    key  --->  #{key}\n"
  RailsPerformance.log "  [SAVE]    value  --->  #{value.to_json}\n\n"
  RailsPerformance.redis.set(key, value.to_json, ex: expire.to_i)
end