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
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('/') == '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
after blocks are written does not ...