Skip to content

Instantly share code, notes, and snippets.

@brighton36
Last active September 14, 2023 19:01
Show Gist options
  • Save brighton36/99aed98142ad02d39ffea372f3087edd to your computer and use it in GitHub Desktop.
Save brighton36/99aed98142ad02d39ffea372f3087edd to your computer and use it in GitHub Desktop.
rails_exercise.rb
start_range = Date.today.beginning_of_month
end_range = Date.today.end_of_month
# Seeing that we don't use these three collections, I would normally remove them, and their associated code here. But,
# Without knowing the greater context of this code, I guess, I'll just leave it be
employers = []
partners = []
controller_resources = []
distinct_groups = {} # username => use_time_in_seconds , see note at bottom
# This should batch in groups of 1000. I have no idea how many users are in the system. So,
# I'm going to assume batches of 1000 are efficient
User.where(role: role).find_each do |user|
time = 0
last_time = nil
# It didn't seem to make sense, to keep a running list of times, when, this counter was the resulting goal...
total_time = 0
# NOTE: I would be inclined to assume we don't need this variable. And could just index distinct_groups
# by user.username. But, without seeing the database, I'll just leave this be.
user_name = nil
# I'm assuming that :user_events is a has_many association. I'm guessing we should also work on this, in batches of 1000....
user.user_events.where('created_at >= ? and created_at <= ?', start_range, end_range).order(:created_at).find_each do |event|
user_name = event.user_name
# I guess, if the user logged in during this event, we append their session (ids?) into an aggregatation, for some reason...
if event.last_known_session.present?
employers << event.last_known_session["employer"]
partners << event.last_known_session["partner"]
end
# Seems like another unused aggregation here.... I 'm going to leave these, as I don't really know the full
# context outside of this segment...
controller_resources << event.data["params"]["controller"]
if last_time.nil? || last_time+10.minutes < event.created_at
# Reset the event duration accrual
total_time += time
time = 0
last_time = event.created_at
else
time += event.created_at - last_time
last_time = event.created_at
end
end
total_time += time
# This stores an approximate total of all time spent on our system (in seconds), within the provided
# start/end range, for each user.
# It seems as if this is an engagement metric. Though, it may be reported to administrators, for the
# purpose of auditing employee hours....
distinct_groups[user_name] = total_time
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment