1. Creating a basic Sinatra Project
Building your first basic Sinatra project
Guides, tutorials and labs to accompany CMU's Programming for Online Prototypes (49-714).
Everything you need to know about building microservices for the web with Ruby and Sinatra.
Remember with routes, everything that goes away after it’s called. Any variables we create are destroyed as soon as the task is completed. But our users are likely to make use of more than one action on our web application. Wouldn’t it be great if we could keep some information around for the next time they do something with our application?
We’ll with sessions we can. Sessions allow us to store bits of information that are just about a single user. Those bits of information are maintained by the web server even after a request completes. That way the next time a user visits, it’ll be available.
To use sessions, you just need to add one line of code to your application (typically at the top)
enable :sessions
Then we can use sessions like this:
get '/' do
"value = " << session[:value].inspect
end
get '/:value' do
# store a parameter in a session
session['value'] = params['value']
end
Let’s look at a basic example, if we wanted to personalize the experience of the application by asking the user to tell us their name:
get '/'
if session["name"].nil?
'Welcome!'
else
'Welcome back ' + session["name"]
end
end
get '/set_name/:name' do
# here we're assigning the parameter
# into a session variable
# this information then persists across
# requests to the webservice
# i.e. the server will maintain this information
# specific to a single visitor / user
session["name"] = params["name"]
"Hello there, " + params["name"]
end
get '/unset_name' do
session["name"] = nil
end
Sidebar: This is essentially how authentication works for most web applications too. Instead of set_name, you have log in. Instead of unset_name you have logout. And then you’d look up the credentials and store them in a session so you don’t have to log in before every single request you make.
Sessions are really useful but you can’t rely on them to be there forerver. They will eventually EXPIRE.
Sessions will disppear after an specified ‘idle time’. Your sessions might also be reset when you restart your server or deploy new code to a remote server.
Keep this in mind as you’re using sessions. It’s great for sharing information between your routes in the short term but it’s not a long term solution.
This series guides you through creating your first Sinatra project and some of the features it offers for creating web-delivered apps
Building your first basic Sinatra project
Building your first basic Sinatra project
Routing with HTTP Methods explained
How to include named parameters in defined routes
Storing User Information in Sessions
How to return a HTTP error response
Using configuration blocks to store application wide variables