Add heartbeats to users & initial seconds calculation

This commit is contained in:
Max Wofford 2025-02-17 12:52:50 -05:00
parent f1742ea8c3
commit aff60c997e
3 changed files with 33 additions and 0 deletions

View file

@ -1,4 +1,6 @@
class Heartbeat < WakatimeRecord
TIMEOUT_DURATION = 2.minutes
def self.cached_recent_count
Rails.cache.fetch("heartbeats_recent_count", expires_in: 5.minutes) do
recent.count
@ -6,4 +8,26 @@ class Heartbeat < WakatimeRecord
end
scope :recent, -> { where("created_at > ?", 24.hours.ago) }
scope :today, -> { where("DATE(created_at) = ?", Date.current) }
# This is a hack to avoid using the default Rails inheritance column Rails is confused by the field `type` in the db
self.inheritance_column = nil
# Prevent collision with Ruby's hash method
self.ignored_columns += [ "hash" ]
def self.duration_seconds(scope = all)
scope.order(created_at: :asc).each_cons(2).sum do |current, next_beat|
time_diff = (next_beat.created_at - current.created_at)
[ time_diff, TIMEOUT_DURATION ].min
end.to_i
end
def self.duration_formatted(scope = all)
seconds = duration_seconds(scope)
hours = seconds / 3600
minutes = (seconds % 3600) / 60
remaining_seconds = seconds % 60
format("%02d:%02d:%02d", hours, minutes, remaining_seconds)
end
end

View file

@ -17,6 +17,10 @@ class User < ApplicationRecord
update!(is_admin: false)
end
def heartbeats
Heartbeat.where(user_id: self.slack_uid)
end
def self.authorize_url(redirect_uri)
params = {
client_id: ENV["SLACK_CLIENT_ID"],

View file

@ -1,4 +1,9 @@
<div class="container">
<h1>Welcome to Harbor</h1>
<p>Your application is ready!</p>
<% if current_user %>
You've logged
<%= current_user.heartbeats.today.duration_formatted %> today across
<%= pluralize(current_user.heartbeats.today.count, 'heartbeat') %>
<% end %>
</div>