Skip to content

Comments

Refactor is_outdated properties for consistent boolean return#188

Open
sujalsom22 wants to merge 1 commit intoOpenLake:mainfrom
sujalsom22:refactor-is-outdated-return
Open

Refactor is_outdated properties for consistent boolean return#188
sujalsom22 wants to merge 1 commit intoOpenLake:mainfrom
sujalsom22:refactor-is-outdated-return

Conversation

@sujalsom22
Copy link

@sujalsom22 sujalsom22 commented Feb 11, 2026

Description

Refactor is_outdated properties for consistent boolean return

Problem

Several is_outdated properties returned None when the condition was false due to using else: False without an explicit return statement.

Solution

Refactored all is_outdated methods to directly return the boolean expression:

return datetime.now(tz=timezone.utc) - self.last_updated > timedelta(minutes=X)

Impact

  • Ensures consistent boolean return values
  • Removes implicit None returns
  • Improves readability and code clarity
  • No functional behavior change

Summary by CodeRabbit

  • Refactor
    • Improved internal code structure for consistency and maintainability across leaderboard data models.

@coderabbitai
Copy link

coderabbitai bot commented Feb 11, 2026

Walkthrough

The api/leaderboard/models.py file was refactored to simplify is_outdated property implementations across five model classes. Verbose if-else statements were replaced with direct boolean expression returns, maintaining all existing threshold values while improving code conciseness.

Changes

Cohort / File(s) Summary
is_outdated Property Refactoring
api/leaderboard/models.py
Simplified is_outdated property implementations in githubUser, openlakeContributor, codeforcesUser, codechefUser, and LeetcodeUser models by replacing explicit if-else returns with direct boolean expressions. All time thresholds preserved (1 or 3 minutes depending on model).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 Five properties, cleaned with care,
If-else branches stripped bare,
Boolean truth, direct and clean,
Shorter code, logic pristine! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the problem, solution, and impact but does not include several required sections from the template: Related Issue(s), Changes (detailed bullet points), Type of Change checkbox selection, and Checklist items. Add missing sections: link related issues if any, provide detailed bullet-point summary of changes, check appropriate type of change box (Refactor), and verify all checklist items are addressed.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Refactor is_outdated properties for consistent boolean return' directly and clearly describes the main change—refactoring is_outdated properties for consistent boolean returns.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link

@check-spelling-bot Report

🔴 Please review

See the 📂 files view, the 📜action log, or 📝 job summary for details.

Unrecognized words (592)
actionlist
addfriend
addlink
aditya
adn
aec
alignof
amazonaws
amqp
antialiased
apexcharts
api
apk
APPS
args
argv
Arial
arrowright
asc
asgi
asm
atlaskit
atn
attr
atv
authtoken
autocomplete
autodiscover
axios
AZERBAIJANI
backend
barcode
bbb
bdsw
bebec
bitbucket
bitcoin
bitset
Bitstream
blang
blinenums
blockquote
blog
bradlc
breadcrumb
bsd
btc
btn
calendarbox
calendarin
calendarlink
calendarnav
Cantarell
ccc
CCPS
CCPSAPI
ccpsleetcoderanking
ccshowfriends
cdata
cdn
changelink
changelist
charset
checkbox
checkboxes
chmod
chooseall
cjs
classmethod
clearall
clickjacking
clockbox
clocklink
clojure
closelink
cls
clsx
cmdk
cnt
cny
codechef
codecheffriends
codeforces
codeforcesfriends
codeforcesuser
collectstatic
colspan
combobox
concat
config
Consolas
constexpr
contenttypes
coreapi
coredocs
cors
corsheaders
cpp
CRA
cred
crontab
csh
csrf
csrftoken
css
curated
curleft
curtop
cva
cxx
dabapps
dadce
dafb
darkmode
dartdoc
datetime
datetimeshortcuts
davegandy
dbaeumer
dblclick
dce
ddd
decltype
dedent
deletelink
deno
deps
describedby
dest
dfd
dirname
DIRS
discription
discussionpost
disscussion
django
djangoproject
Dmitriy
dnd
dnt
dockerfile
doctype
dotenv
downcode
Downcoder
draggable
drf
dribbble
DRILLDOWN
Droid
dropbox
dropdown
dropfriend
droppable
eaed
ececf
edecd
eee
efb
ele
elems
elif
elsif
enctype
endif
entrypoint
enum
EOL
eot
errexit
errorlist
errornote
esac
esbenp
eslint
eur
facebook
favicon
fbfbfc
fdd
Fefer
fetchall
ffc
ffefef
fff
fieldset
fieldsetcollapser
filteredusers
findpos
Fira
flatpage
flickr
fontawesome
fontawesomeregular
foreach
formset
fromtimestamp
frontend
func
gamepad
gbp
getccfriends
getcffriends
getenv
getghfriends
getltfriends
gettext
ghshowfriends
github
githubfriends
githubusercontent
gittip
globals
glyphicons
gmail
gohri
google
GOOGLEDATA
gotop
graphql
grayscale
GSo
halflingsregular
hdd
heatmap
hexcolor
hiddenfields
hljs
Holovaty
hookform
horiz
howto
href
hsl
htm
html
http
Hyperlinked
icnt
ico
iefix
ifdef
ifndef
img
inbox
INITDB
inlinechangelink
inlines
inlineviewlink
inp
inr
insertapi
Insitute
instagram
instanceof
INTV
isoformat
isready
Jannis
javadoc
javascript
javascriptreact
jpg
jpy
jsguide
json
jsx
jti
jumbotron
jumotron
JWK
jwt
keydown
keyframes
keyup
krw
kwargs
kwd
kwv
lbh
Lconf
leaderboard
leaderboardpro
leetcode
leetcodecontestrankings
leetcodefriends
leetcoderanking
leetcoderankingccps
leetcoderankingsccps
Leetocde
Leidel
len
Lexer
lify
lightgrey
linenums
linkedin
linting
linux
linuxhint
localhost
lockfile
lodash
loglevel
logresponse
lsaquo
LTshowfriends
lucide
madueke
majodev
makemigrations
maxcdn
maxlength
medkit
meh
Memon
messagelist
metadata
Microsoft
middleware
mixin
mjs
mongodb
moz
mozilla
mql
multiline
mxml
namearr
namespace
navbar
ndx
Neue
ngettext
nginx
nocode
nodejs
nodesource
nonday
noreferrer
normarr
noscript
nowrap
npm
npx
nullptr
nums
offcanvas
ofhiuvw
OFL
oklch
onrender
openlake
opensource
opentype
opn
orderby
osx
outdent
pagelines
paginator
params
pathlib
perl
pgettext
Phalip
php
phpdoc
pinterest
pln
plugin
png
pnpm
Polovnyov
Polyfill
popup
postgre
postgresql
Powershell
PPK
pragma
prepopulate
prepopulated
prettyprint
progid
pyguide
pylint
pymongo
pypi
PYTHONPATH
qrcode
queryset
Quicklink
quirksmode
qyu
rabbitmq
radiolist
reactjs
readonly
redis
redislabs
regex
regexp
regresponse
reinit
renren
replypost
resizable
retweet
rgba
rmb
rmq
Roboto
robotstxt
rohit
rpdttenqphkdyvpuoeky
rsaquo
rsc
rss
rstrip
rtl
runserver
sbyte
scrollbars
scss
sdk
searchbar
searchfield
Segoe
selectfilter
selectfilterstacked
serializer
setattr
setcontestoptions
setdefault
setis
shadcn
showall
simplejwt
sitemap
sizeof
skype
solvedc
solvedl
sortoptions
sortpriority
sortremove
sqlite
src
stackalloc
stan
standalone
startproject
staticfiles
stderr
stdout
strftime
strictfp
strikethrough
stringify
strptime
stswe
styleguide
subdir
substr
sudo
Sumagna
sumagnadas
supabase
svg
svgr
svh
Swicegood
sys
tabbable
tabstyle
tailwindcss
tanstack
tbody
textarea
textfield
tfoot
thead
timedelta
timelist
timezone
timezonewarning
todisplayusers
TODO
toolbar
tooltag
tooltip
toplinks
trello
tripathi
truetype
tsx
ttext
ttf
TTFB
ttg
tumblr
typedef
typeid
typename
typeof
uage
ubuntu
uid
uint
ulong
uname
undef
unicode
unmounts
unsubscribe
upvotes
uri
url
URLCONF
urlencode
urlencoded
urlify
urllib
urlpatterns
usd
username
userphoto
userpic
usertasks
ushort
usr
utc
utf
utils
UUID
UXux
validator
venv
vercel
verdana
vhdl
VHOST
viewlink
viewsets
viewsitelink
vimeo
visualise
vitejs
vitest
vmin
vnd
vscode
vue
wantarray
webfont
webkit
webpack
website
weibo
whiteants
whitenoise
wiki
winutils
woff
WORKDIR
wsgi
www
xae
xaxis
xcode
XFrame
xfull
xhr
XHT
xhtml
XIcon
xing
xlink
xml
xmlns
xmp
XReg
xsl
xss
yaml
yapf
yaxis
youmightnotneedjquery
youtube
yuaoh
yzo
Some files were automatically ignored 🙈

These sample patterns would exclude them:

(?:^|/)__init__\.py$
(?:^|/)codechef\.svg$
(?:^|/)github\.svg$
(?:^|/)leetcode\.svg$
(?:^|/)pnpm-lock\.yaml$
[^/]\.eot$
[^/]\.ttf$
[^/]\.woff$
^\Qapi/staticfiles_build/static/rest_framework/docs/js/highlight.pack.js\E$
^\Qapi/staticfiles_build/static/rest_framework/js/coreapi-0.1.1.js\E$
^api/leaderboard/contest_data\.json$
^api/requirements\.txt$
^api/staticfiles_build/static/admin/img/gis/
^api/staticfiles_build/static/rest_framework/fonts/glyphicons-halflings-regular\.woff2$
^app/dump\.rdb$
^app/src/logo\.svg$

You should consider excluding directory paths (e.g. (?:^|/)vendor/), filenames (e.g. (?:^|/)yarn\.lock$), or file extensions (e.g. \.gz$)

You should consider adding them to:

.github/actions/spelling/excludes.txt

File matching is via Perl regular expressions.

To check these files, more of their words need to be in the dictionary than not. You can use patterns.txt to exclude portions, add items to the dictionary (e.g. by adding them to allow.txt), or fix typos.

To accept these unrecognized words as correct and update file exclusions, you could run the following commands

... in a clone of the git@github.com:sujalsom22/Leaderboard-Pro.git repository
on the refactor-is-outdated-return branch (ℹ️ how do I use this?):

curl -s -S -L 'https://raw.githubusercontent.com/check-spelling/check-spelling/main/apply.pl' |
perl - 'https://github.com/OpenLake/Leaderboard-Pro/actions/runs/21924100548/attempts/1' &&
git commit -m 'Update check-spelling metadata'
Available 📚 dictionaries could cover words not in the 📘 dictionary
Dictionary Entries Covers Uniquely
cspell:django/dict/django.txt 393 62 18
cspell:software-terms/dict/softwareTerms.txt 1288 106 15
cspell:python/src/common/extra.txt 741 20 13
cspell:npm/dict/npm.txt 302 46 10
cspell:fullstack/dict/fullstack.txt 419 41 7

Consider adding them (in .github/workflows/spelling.yml) in jobs:/spelling::

      with:
        extra_dictionaries: |
          cspell:django/dict/django.txt
          cspell:software-terms/dict/softwareTerms.txt
          cspell:python/src/common/extra.txt
          cspell:npm/dict/npm.txt
          cspell:fullstack/dict/fullstack.txt

To stop checking additional dictionaries, add (in .github/workflows/spelling.yml):

check_extra_dictionaries: ""
Warnings ⚠️ (4)

See the 📂 files view, the 📜action log, or 📝 job summary for details.

⚠️ Warnings Count
⚠️ binary-file 15
⚠️ minified-file 1
⚠️ noisy-file 4
⚠️ single-line-file 10

See ⚠️ Event descriptions for more information.

If you see a bunch of garbage

If it relates to a ...

well-formed pattern

See if there's a pattern that would match it.

If not, try writing one and adding it to the patterns.txt file.

Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

Note that patterns can't match multiline strings.

binary-ish string

Please add a file path to the excludes.txt file instead of just accepting the garbage.

File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
api/leaderboard/models.py (1)

48-48: ⚠️ Potential issue | 🟠 Major

Pre-existing bug: default is evaluated once at class-definition time.

default=datetime.now().timestamp() is evaluated when the module loads, so every new codeforcesUser instance gets the same stale timestamp. This should use a callable instead.

🐛 Suggested fix
-    last_activity = models.BigIntegerField(default=datetime.now().timestamp())
+    last_activity = models.BigIntegerField(default=0)

Or if a dynamic default is intended:

def _default_timestamp():
    return int(datetime.now(tz=timezone.utc).timestamp())

# then in the model:
last_activity = models.BigIntegerField(default=_default_timestamp)
🧹 Nitpick comments (1)
api/leaderboard/models.py (1)

22-22: Optional: prefer django.utils.timezone.now() over datetime.now(tz=timezone.utc).

Django's timezone.now() respects the USE_TZ setting and is the idiomatic choice in Django projects. This is a pre-existing pattern, so fine to defer.

♻️ Example
-from datetime import datetime, timedelta, timezone
+from datetime import timedelta
+
+from django.utils import timezone

Then in each property:

-        return datetime.now(tz=timezone.utc) - self.last_updated > timedelta(minutes=1)
+        return timezone.now() - self.last_updated > timedelta(minutes=1)

Also applies to: 35-35, 56-56, 120-120

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant