Skip to content

Instantly share code, notes, and snippets.

@Chrissiku
Created September 13, 2023 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chrissiku/f38eaf07b4233ef004f9961fef554d39 to your computer and use it in GitHub Desktop.
Save Chrissiku/f38eaf07b4233ef004f9961fef554d39 to your computer and use it in GitHub Desktop.
# Background:
#after full refactor of the provided code to make it more efficient I added comments to improve readability.
#I'll also address your questions about the 'distinct_groups' variable and what it contains.
start_range = Date.today.beginning_of_month
end_range = Date.today.end_of_month
# Fetch users with the given role efficiently using the database query.
users = User.where(role: role)
employers = []
partners = []
controller_resources = []
distinct_groups = {}
# Iterate through users.
users.each do |user|
times = []
last_time = nil
user_name = nil
# Fetch user events within the specified date range.
user_events_filtered = user.user_events.where(created_at: start_range..end_range).order(:created_at).to_a
# Iterate through filtered user events.
user_events_filtered.each do |event|
user_name ||= event.user_name
last_known_session = event.last_known_session
controller_params = event.data["params"]
if last_known_session.present?
employers << last_known_session["employer"]
partners << last_known_session["partner"]
end
controller_resources << controller_params["controller"]
# Calculate time intervals between events.
if last_time.nil? || last_time + 10.minutes < event.created_at
times << 0
else
times << event.created_at - last_time
end
last_time = event.created_at
end
# Calculate the sum of time intervals for this user.
sum = times.sum
distinct_groups[user_name] = sum
end
# 2. Please explain what the variable 'distinct_groups' will contain by the end of the execution and what
# this data would be useful for.
# The 'distinct_groups' variable is a hash where the keys are user names, and the values are the total time intervals
# spent between their user events within the specified date range. It will contains information about how much time each
# user has spent interacting with the system during the specified time period. This data can be useful for various
# analytics and reporting purposes, such as identifying which users are the most active or which areas of the
# application are getting the most user engagement.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment