Skip to content

Instantly share code, notes, and snippets.

@shanelonergan
Last active February 9, 2022 01:01
Show Gist options
  • Save shanelonergan/b86a6704ca1e7d7c9a4a610c8f363ee6 to your computer and use it in GitHub Desktop.
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
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