DEV Community

Cover image for Sinatra web app, Gemstone Groupies
Michael Thornton
Michael Thornton

Posted on

Sinatra web app, Gemstone Groupies

Sinatra

When building a simple web app Sinatra is very handy it translates our ruby code into http requests and makes it very easy to build upon. When you create a controller class then inherit from Sinatra Base this ruby class is now ready to use methods like Get and Post. These methods in our controller class tell Sinatra what kind of request is being called and what to do with it.

Getting Setup

Sinatra web apps can be very easy to build out and made even easier thanks to a ruby gem called corneal. This gem gives the basic skeleton of a Sinatra app and a great starting point. If you are interested check it out HERE.

Gemstone Groupies

I have a passion for gemstones so I created an app that would allow fellow "groupies" to connect with each other. First off you would have your own gemstones and then view those stones related to you. Then I added the function to view other peoples collections. The last piece that I made for my app was the ability to comment on others gemstone collection.

MVC

Model, View, Controller: This is the flow of the Sinatra app and it makes it so much easier to build out the relationships required for Active Record to persist your data, make your html files, and contoller classes. The models are ruby classes that inherit from Active Record and this is where I made the relations of a User has many gemstones and a gemstone belongs to a user.User model for Gemstone Groupies
Next the view files, they are exactly what you would think. These files are what a user would actually see when running your app in the browser. This is where I filled in the html for a browser to read.
Alt Text
Then you have the controller files, here is where a little Sinatra magic happens. In the controller you are directing your app. You have to specify where to go when a URL is called. Using the Get method Sinatra grabs that URL request from the browser and then you direct it to the view associated with it. It is very important to remember that you have to include each controller in the config.ru file or the app will have no clue where to look for the URL.Alt Text

Sessions and Protections

Enabling sessions and setting a secret key for the app in the application controller makes it possible to store cookies in the app and the browser and lets the app read this info. So now when a user is signed in they get a key of user_id and value set to there id in the database. With this I was able to create a helper method that was called before any requests were processed in the app.Alt Text

Conclusion

Sinatra is very handy and the corneal gem makes your life a lot easier when getting started. making a web app doesn't have to be a daunting task and persisting the data is as easy as Gemstone.create. If you would like to see my app you can get it here > Gemstone Groupies

Top comments (0)