session is nil initially

49 views
Skip to first unread message

DAZ

unread,
Feb 10, 2020, 12:30:28 PM2/10/20
to sinatrarb
I have some basic code for a guess the number game (see below)

However, on the first post request after starting the server, I often get the error message that `session[:attempts]` is nil and the + method cannot be used:

NoMethodError at /guess

undefined method `+' for nil:NilClass


This error then goes away for all subsequent requests. I think the problem must be something to do with how Rack handles sessions, but can't think what it is. Anybody got any ideas?

Thanks,

DAZ

Code below:


require 'sinatra'

enable :sessions
enable :inline_templates

get '/guess' do
  session[:number] = rand(1..100)
  session[:attempts] = 0
  @message = "I'm thinking of a number between 1 and 100, try and guess what it is. Attempts: #{session[:attempts]}"
  erb :guess
end

post '/guess' do
  number = session[:number]
  guess = params[:number].to_i
  session[:attempts] += 1
  redirect to('/success') if guess == number
  if guess < number then @message = "Too small, try again."
  elsif guess > number then @message = "Too big, try again."
  end
  erb :guess
end

get '/success' do
  attempts = session[:attempts]
  "Well done, you guessed my number in #{attempts} attempt#{'s' if attempts > 1}!"
end

__END__

@@guess
<!doctype html>
<html>
  <header>
    <title>Guess the Number</title>
  </header>
  <body>

    <p><%= @message %></p>
    <form method="POST" action="/guess">
      <input name="number">
      <input type="submit" value="Guess">
    </form>
  </body>
</html>

Andrew Premdas

unread,
Feb 13, 2020, 6:15:49 AM2/13/20
to sina...@googlegroups.com
If you restart the server and the first request is a post, then your new session hash won't have the attempts key so

session[:attempts] == nil

and your code in your post session[:attempts] +=1 is actually nil += 1

and nil += 1  gives undefined method + for nil error

You could try something like

session.key[:attempts] ? session[:attempts] +=1 : session[:attempts] = 1

which would  get you past your bug.

--
You received this message because you are subscribed to the Google Groups "sinatrarb" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sinatrarb+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sinatrarb/ee274f20-723a-48f1-921d-14b80e69a436%40googlegroups.com.


--
------------------------
Andrew Premdas

DAZ

unread,
Feb 14, 2020, 5:39:10 AM2/14/20
to sinatrarb
Thanks Andrew - that makes sense, although I thought the first request was the get request after restarting the server, but maybe it was cached?

I like your idea anyway - makes it a bit more bulletproof!

Cheers,

Daz
To unsubscribe from this group and stop receiving emails from it, send an email to sina...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages