patternrubyrailsMinor
Find existing session
Viewed 0 times
existingsessionfind
Problem
I have this method in my rails app:
It retrieves all the
If it can't find a
This is pretty easy, but it seems to be a lot of if/else for such a straightforward thing.
def find_or_create_session(fbid)
@sessions = Session.all
if @sessions.find_by facebook_id: fbid
@session = @sessions.find_by facebook_id: fbid
if ((Time.now - @session.last_exchange).fdiv(60)).to_i > 5
@session = Session.create(facebook_id: fbid, context: {})
end
else
@session = Session.create(facebook_id: fbid, context: {})
end
@session
endIt retrieves all the
Sessions, and tries to find one with a given facebook_id. If there is one, it checks if it's a recent one (last_exchange was less than 5 minutes ago). If it's not, it creates a new one. If it can't find a
session for this facebook_id, it will create one.This is pretty easy, but it seems to be a lot of if/else for such a straightforward thing.
Solution
Some notes:
I'd write:
@session: A method calledfind_or_create_sessionshould not change the state of instance variables.
@sessions.find_by facebook_id: fbidis written twice. Use variables to avoid repetition. Also, the consensus in the Ruby community is to always write parens (except for DSL-like code).
Time.now - @session.last_exchange: You can perform that check in the SQL query.
- Your method is basically doing
find_or_create_session = existing_session || new_session, let the code mimic it.
I'd write:
def find_or_create_session(fbid, max_age: 5.minutes)
Session.find_by(["facebook_id = ? AND last_exchange >= ?", fbid, max_age.ago]) ||
Session.create(facebook_id: fbid, context: {})
endCode Snippets
def find_or_create_session(fbid, max_age: 5.minutes)
Session.find_by(["facebook_id = ? AND last_exchange >= ?", fbid, max_age.ago]) ||
Session.create(facebook_id: fbid, context: {})
endContext
StackExchange Code Review Q#126744, answer score: 4
Revisions (0)
No revisions yet.