Flash Error Messages on a Sinatra Knicks app.

Muhammad Musah
2 min readAug 25, 2020

--

For my Sinatra project I built an app that would pique my interest through my passion…the Knicks. Since they’re a bad team I chose to make an app that would allow users to post grievances about different players on the team. Knicks grievances had 4 models. Users, Players, Grievances, and PlayerGrievances. The most challenging aspect of the project was adding flash error messages. In this blog I’ll walk you through how I did that.

My first challenge was realizing that I had to use the ‘sinatra-flash’ gem in ‘app/Gemfile’, I added it like so:

gem 'sinatra-flash'

The next step is to also enable flash in the configuration block of the Application Controller like so:

class ApplicationController < Sinatra::Baseconfigure doset :public_folder, 'public'set :views, 'app/views'enable :sessions unless test?set :session_secret, "secret"register Sinatra::Flashend

Once you realize that you have to add those single lines of code to those files, it’s time to implement them! In my app I wanted to make it impossible to edit a grievance for anyone who did not create that grievance. I also wanted to notify the user when a grievance is successfully deleted. In order to make that possible we have to go to the Grievance controller:

delete '/grievances/:id' do   find_my_grievance  if authorized_to_edit?(@grievance)   @grievance.destroy   flash[:message1] = "Successfully deleted your grievance!"   redirect '/grievances'  else   flash[:message] = "You can't delete someone else's grievance!"   redirect "/grievances/#{@grievance.id}"  endend

These lines of code were responsible for the logic of how the flash error will render. Once the grievance is deleted, flash[:message1] is fired up, the message will then render on the page that you tell it to redirect to. If it does not successfully delete because the user is not authorized to edit, flash[:message] will be rendered. Now that we have the logic done, it’s time to actually show it on the view page.

<%if flash[:message1] %><h3><%= flash[:message1] %></yh3h3><% end %>

We introduce the flash message with an embedded ruby conditional that tells the rendered page to show the error message if the grievance controller says so. Hopefully you’ll end up with something like this!

Note: The page is technically “redirecting”, I’m just using the word “render” because I want to.

Flash error message works!

So we’ve learned how to use these the ‘sinatra-flash’ gem in order to implement it on the appropriate controller and render it using the view page! Now you have the tools to alert users of all types of occurrences in your Sinatra app.

--

--

No responses yet