Building a Sinatra App in Ruby
By: Stuart Alex Fleishman
Tags: Sinatra App, Ruby

Building a Sinatra App in Ruby

Making a Web App in Sinatra is quite easy. First, just make sure you have Ruby and Sinatra installed. Then install a handy gem called Corneal. After you install Corneal, simply type corneal new APP-NAME. If any of this is confusing you, here is a link to the corneal website. https://thebrianemory.github.io/corneal/

After you have typed corneal new APP-NAME, you need to CD into the app with the name you have given it, and then run bundle install or just bundle for short. Then open your project. If you are using VS code and have the shell path set up, you can simply type code . and your VS code will open up with all the corneal files. Note that is code . with the period(.) If any of that was confusing here is a link to setting up that function. https://code.visualstudio.com/docs/setup/mac

The beauty of using the corneal gem, is that it has already set up a bunch of gem for you, and it has established a database using sqlite3. It has also set up active record and some rake commands. If you are unfamiliar with databases/sqlite 3, I would suggest watching some YouTube videos on the subject. Understanding databases and in particular how they assign primary key IDs will be critical for setting up your active record associations. If this is confusing, I would suggest watching some YouTube videos on active record as well as object-relational mapping(ORM), and CRUD(create read update delete).

Ok, so once you have your corneal app open, the first thing we need to do is think about our tables. What table will be the one that has_many? In this example, we will use two tables, a User and FamilyMember. So you would say that a User has_many FamilyMembers. And a FamilyMember belongs_to a User. Cool. Now, with this information we can create our tables. It is very important when creating tables in Ruby that we remember that a table be pluralized. Subsequently, your Model will be singularized. With some words in Ruby, it doesn’t follow grammatically correct English. For example, the plural version of deer is deer; however, in Ruby for your table it would be deers. If ever in doubt, we can call the pluralize method on any object and it will give the pluralized version of the word that Ruby will accept. In the example above, the pluralized version of User is Users. Creating a table is very simple with corneal, thanks to some rake functions that have been created for us. To see a full list of rake functions, simple type in rake -T into your terminal, and a list of the rake functions will appear. In our case, we will type into the terminal rake db:create_migration NAME= “create_users”. Now a new file will appear under your db/migrate folder. In the file you will see…

class CreateUsers < ActiveRecord::Migration. This lets us know that the class is inheriting some cool functions from ActiveRecord Migration. Here’s a link to full documentation regarding migrations. https://guides.rubyonrails.org/active_record_migrations.html.

Cool, so now we just need to specify our table and column names and types. It will look like this.

You will have to write out the create_table then your pluralized table name, then do |t| for table helpers, and then we specify what type we want the column to be. In this case, all them are strings. Also, you will notice the use of password_digest. Password digest is used for a couple reasons. First, the gem bcrypt and second because of has_secure_password. The gem is a hashing algorithm. This means when a user creates a password that is 1234, bcrpyt is going to change the password to look something like this Aasdf123$5!!90zkl. This is because if a hacker were to get into your database, they would be able to see what each user’s password is…not good. On top of changing the password, because hackers also have dictionary passwords, which aim to match up to the changed version of the password, bcrypt will also add in a random string. This is known as “salt”. Then the has_secure_password, which goes in your model, gives us accesses to an authenticate method. This will come in handy later when validating users for login. Also side-note, that since we wrote one line of code that wrote other lines of code for us, we just did something known as metaprogramming. Now we are getting geeky! Also! Please note that even though when we created our table and said password_digest, we won’t call it later like this. We will simply call it via password. Alright, so now that we have our table set up, we need to migrate it. To do this simply type in rake db:migrate into your terminal. If everything worked correctly, you should be able to go into your schema and see the table. BUT, never touch the schema. The schema is simply a window into your database. If you touch the window, it will break, because it’s made with cheap glass. Just kidding, the glass is really nice, but just don’t ever touch the schema. Cool, so now we have to create our other table. This one we will call familymembers. So type in rake db:create_migration “create_family_members.” Now, even though we haven’t created the models yet, we know that this will be our belongs_to table, which means it has to get the foreign key. The foreign key will allow us to know what family member belongs to what user, because it will take the primary key from the user and assign it to the family member.

Please note, I made a mistake when creating the table name and did not call the table family_members as I did when doing the rake db:create_migration. Whenever changing a Migration, it is always best practice to create a new migration instead of rolling back. If you roll back, you could loose data.

Alright! So now we have our tables set up. Now, we gotta create some models. Fun! Remember, models are going to be singular. Here’s what my User model looks like.

As you can see, the User class is inheriting from ActiveRecord::Base, and also has some ActiveRecord validations. These validations, will pretty much do just as they say in the line of code, and will give us access to an errors method, which we can then get messages from to return to the user. More on this in a bit. Also, here is my FamilyMember model.

The next step if you want to be a pro, and I’m assuming you do, would be to make sure that everything works! Corneal gives us access to something called Tux. It’s kind of like a pry or an irb session. Simply type in Tux into your terminal and see if you can create a User. Type tony = User.create(name: “Tony”). Or, kate = Familymember.create(name: “kate). Then see if your associations work. Can you type in Tony.family_members.create(name: “Rachel”)? If so, then we are good to create a seed file so our app will have some data to play around with. In your terminal type, touch db/seeds.rb. Then in your seeds file do something like this.

Cool. Now type in rake db:seed. Sweet, now it’s time to make some controllers. It’s important to note that the controllers will follow something known as RESTful routing. This is simply an industry standard way to write your routes, making it easier to collaborate with people, as everyone will be on the same page. Here’s a link about this.

So, before we make our User_Controller, we are going to do something very important, and that is to set up some sessions. Sessions are going to allow to us create an empty hash, that we will validate users with in our helpers. Let’s take a look at our application controller.

So you can see under configure, you enable the session then set it. The methods in helpers will allow us to see if a user is logged in, and find a current current. Then finally we have the first route of our app, a simple “/”, that is rendered by a erb :welcome. Here’s what that erb file looks like. Also, erb just means embedded ruby. We are simply using ruby, inside of html. Anytime we want to write ruby code to be used in an erb but not seen we will do this, <% ruby code goes here %>. And if we want to show the ruby code, do the same except with an =. Looks like this <%= ruby code that is seen %>

Here we just have some simple html, with some CSS. This file goes to a layout that is part of corneal, and it knows where to go via a <%= yeild %>. Let’s take a peek out the layout. Also, all the CSS for this project was done with materalizecss.

In this layout, you can see I have some conditional statements going on where I call the helpers method to either display login/logout/signup and a home button. Then below, where the yield is happening, the erb welcome file is rendered. Neat. And here are the other controllers.

Here note the use of params. Params are just the information we are getting from the user via our form.

By calling params[:user] we get access to their user_name, email, and password that we then call on the class User to make a new instance of the user. And remember those validations in the User model? Well, they gave us access to those error message that we used. Also note, that we only have access to the error message in an erb file because we made it an instance variable. Cool, let’s peak at the FamilyMember Controller, which has full CRUD function.

Also, very important to note that every controller after your Application Controller, will inherit from the Application Controller. And you MUST, go into your config.ru and write in use ControllerName, in order for each controller to work.

The Rack::MethodOverride will be used for the Patch/Delete forms as Sinatra does not work well with those functions. Basically what happens is that it will look for anything with a “_method” in the form.

Going back to the FamilyMember Controller, notice the use of the routes with :id in it. These types of routes are known as dynamic routes. It allows us to pretty much have an infinite number of those routes without having to hard code it. But beware, these dynamic routes need to go towards the bottom of the controller, or Sinatra will get confused when calling some of the other routes and think you are trying to call the dynamic one. I.E. if you had the route ending in new after :id, when you went to call the new, it would load the :id route. And lastly, let’s take a look at the SessionsController.

Notice the use of the authenticate method. This comes from has_secure_password. And there you have it. A Sinatra App, that let’s Users signup, logout, login, and create and destroy things. Up next, I tackle Rails.