O'Reilly logo

Learning Sinatra by Manoj Sehrawat, Sudeep Agarwal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Understanding before and after blocks

There are times when we need to execute a piece of code before (or after) executing any route. To avoid writing such codes repetitively, we can use the before or after block as required. As the name suggests, the before block gets invoked before the route is executed and the after block gets invoked after the route is executed.

In our case, we need to check the validity of the user's session before executing the route. So, we will add the following code:

    14	before do
    15	  if not request.path_info.split('/')[1] == 'login' and session[:user_id].nil?
    16	    redirect '/login'
    17	  end
    18	end

This block will be invoked for every route. Note that the order in which the routes or the before/after blocks are written does not ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required