Last active
February 9, 2022 01:01
-
-
Save shanelonergan/b86a6704ca1e7d7c9a4a610c8f363ee6 to your computer and use it in GitHub Desktop.
Example code for tracker number of consecutive days a User performs a Session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ApplicationRecord | |
has_many :sessions, -> {order "created_at DESC"} | |
def streak | |
streak_count = 0 | |
today = Time.now.to_date | |
dates_array = self.sessions.map do | session | | |
session.created_at.to_date | |
end | |
unique_dates = dates_array.uniq | |
unique_dates.reduce(today) do | memo, date | | |
yesterday = memo.yesterday.to_date | |
if date == yesterday || date == today | |
streak_count += 1 | |
memo = date | |
end | |
end | |
streak_count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment