Class: Stats::Middleware::StatsReporter
- Inherits:
-
Object
- Object
- Stats::Middleware::StatsReporter
- Defined in:
- lib/stats/middleware/stats_reporter.rb
Instance Method Summary collapse
- #display_summary(days: 30, limit: 10) ⇒ Object
-
#initialize(redis:, redis_key_prefix: 'api_requests') ⇒ StatsReporter
constructor
A new instance of StatsReporter.
- #summary(days: 30) ⇒ Object
- #summary_report(days: 30, limit: 10) ⇒ Object
Constructor Details
#initialize(redis:, redis_key_prefix: 'api_requests') ⇒ StatsReporter
Returns a new instance of StatsReporter.
6 7 8 9 |
# File 'lib/stats/middleware/stats_reporter.rb', line 6 def initialize(redis:, redis_key_prefix: 'api_requests') @redis = redis @redis_key_prefix = redis_key_prefix end |
Instance Method Details
#display_summary(days: 30, limit: 10) ⇒ Object
63 64 65 |
# File 'lib/stats/middleware/stats_reporter.rb', line 63 def display_summary(days: 30, limit: 10) puts summary_report(days: days, limit: limit) end |
#summary(days: 30) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/stats/middleware/stats_reporter.rb', line 11 def summary(days: 30) user_agents = {} ips = {} # Collect data for the specified number of days days.times do |i| date = (Date.today - i).to_s # Collect user agents ua_key = "#{@redis_key_prefix}:#{date}" if @redis.exists?(ua_key) @redis.zrevrange(ua_key, 0, -1, with_scores: true).each do |agent, count| user_agents[agent] ||= 0 user_agents[agent] += count.to_i end end # Collect IPs ip_key = "#{@redis_key_prefix}:ips:#{date}" if @redis.exists?(ip_key) @redis.zrevrange(ip_key, 0, -1, with_scores: true).each do |ip, count| ips[ip] ||= 0 ips[ip] += count.to_i end end end { user_agents: user_agents, ips: ips, days: days } end |
#summary_report(days: 30, limit: 10) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/stats/middleware/stats_reporter.rb', line 45 def summary_report(days: 30, limit: 10) stats = summary(days: days) output = [] output << "=" * 80 output << "API Usage Statistics Summary" output << "=" * 80 output << "Period: Past #{days} days" output << "-" * 40 output << format_user_agents(stats[:user_agents], limit: limit) output << format_ips(stats[:ips], limit: limit) output << format_totals(stats[:user_agents], stats[:ips]) output << "=" * 80 output.join("\n") end |