What is Ruby?

Ruby is a pure object-oriented programming language. It was created by Yukihiro Matsumoto in Japan in 1995. It is a dynamic open-source language that has a great community behind it. It was designed for simplicity and productivity. Ruby encourages writing software code for humans first and computers second.

What is Rails?

Rails is a development framework, written in Ruby, for building web applications. It was created as the foundation of the Basecamp application and then released as open-source software in 2004 for everyone to use.

It was created by David Heinemeier Hasson popularly known as DHH. It is one of the most influential and popular tools for building web applications. It offers many standard features and functionality built-in, which makes it a suitable option for your MVP prototyping and development. It is used by some of your favorite sites like Airbnb, Github, Shopify, etc.

In this beginner's tutorial, you will learn:

Why Rails?

Here, are pros/ benefits of using Rails:

  • Rails is packaged as a Ruby gem, and you can use it to build a variety of applications.
  • It allows you to build regular web applications, e-commerce applications, content management system, and more.
  • Rails is a full-stack framework that includes everything you need to create a database-driven web application, using the Model-View-Controller pattern.
  • This means that all the layers are built to work seamlessly together with less code. It requires fewer lines of code than other frameworks.

Installing Ruby on Windows

The installation process will depend on your operating system. You will go through installing Ruby on Windows, Mac, and Linux.

The easiest way to install Ruby on your Windows computer is through Ruby Installer which you can download at https://rubyinstaller.org/.

All you have to do is run the downloaded installer.

Step 1) Double-click on downloaded installer 'rubyinstaller-2.4.1-2-x64.exe'.

Step 2) Select the 'I accept the license' radio button and click the 'Next' button. This should bring you to the next Figure below:

Step 3) Check the first two checkboxes to make running Ruby scripts easier.

Click the 'Install' button to get the Installation started. You should see the Figure below when the Installation completes.

Step 4) Do not uncheck the checkbox option that installs MSYS2. Click "Finish" to complete the Installation and a command prompt window shown in the Figure below will be displayed.

Step 5) This step installs MSYS2, a building platform that features a package manager for easy Installation of packages on Windows.

Press Enter to install all the components as they are all required to have a smooth Ruby on Rails development environment to work with on Windows.

Installing Rails

You should have Ruby installed from the previous section, and now you are going to install Rails. You can install Rails using a package from RailsInstaller, but the problem with this is that you don't get the latest version of the required packages.

If you have already have the latest Ruby and a baseline set of required RubyGems and extensions installed. All you need do now is run the following command at the command prompt to get Rails on your system: 'gem install rails.'

You will also need to install Node.js if you don't already have it because some libraries that Rails depends on require a Javascript runtime to work correctly. You can get node at https://nodejs.org .

It is a more common and preferred approach to developing on Windows. Rails community uses a Windows Subsystem for Linux that provides a GNU/Linux environment with command-line tools, utilities, and common applications directly on Windows.

Installing Ruby on Mac

Your Mac already has Ruby pre-installed on it. However, the pre-installed version might be old, and so you will need to install a new/latest version.

The easiest way to do this is by using a package manager such as Homebrew. You might first need to install Homebrew by running the command below at the Terminal.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)

This will display a warning and ask you to enter your password. Enter your Mac password (you won't see the characters as you type). Just press 'Enter' when you are done typing your password. Then run this simple Homebrew command to install Ruby on your Mac.

brew install ruby

And also run this command:

echo "export PATH="/usr/local/bin:/usr/local/sbin:$PATH >> ~/.bash_profile

To set this Ruby installation as the default Ruby to run on your system and not the pre-installed Ruby.

To confirm the Installation was successful, you can run the following at the Terminal

ruby --version

this will print the Ruby version number you have installed. The output will look something like

ruby 2.6.0p0 (2018-12-25 revision 66547) [x86_64-darwin18] 

Installing Ruby on Ubuntu (Linux)

The easiest way to get Ruby installed on your Ubuntu system is through the apt package manager. You need to run the following commands at the Terminal to install the latest Ruby from Ubuntu repositories.

  • sudo apt update – This will update the default Ubuntu repositories
  • sudo apt install ruby-full – It will download and installs the latest Ruby

To confirm the Installation was successful, you can run the following 'ruby --version,' this will print the Ruby version you have installed.

Installing Rails on Ubuntu (Linux)

You should follow the steps below to successfully install Rails on your Linux machine.

Step 1) Update your computer gem manager by running 'gem update –system' at the Terminal or command prompt.

Step 2) Run 'gem install rails' to install the latest version of Rails on your computer.

Step 3) You should install bundler gem for easy Rails application gem dependency management. Run 'gem install bundler' to get it.

Two principles of Rails

Rails follow basic software design principles and encourage you to use those principles too.

The two most common are:

  • Don't Repeat Yourself (DRY) – this makes you write concise, consistent, and maintainable code.
  • Convention over Configuration – Rails is pre-configured to use sensible defaults that fit most common usage. This makes your application development fast, and you also have less code to maintain.

Rails – Project File Structures

With Rails now installed on your system lets create a Rails application! You will learn to create a Todo list application in this tutorial. Run the following command 'rails new todo_app' in your Terminal to create the application.

This command creates a directory named 'todo_app' in the current directory with the basic folder structure of a Rails web application, as shown in the Figure below:

You will go through the main directories in this section.

app – This directory groups using different subdirectories for the UI/layout (views and helpers), the controller (controllers files) and the models (business/application logic).

app/controllers – This directory stores controller files used by Rails to handle requests from the client.

app/assets – It contains static files, which is a need for the application's front-end grouped into folders based on their type – Javascript files, images, and stylesheets.

app/helpers – This subdirectory contains helper functions that make your application model, view, and controller logic focused, small and uncluttered.

app/models – This contains files

that model your application's database. The model classes make working with the database very easy.

app/views – This hold template/layout files the user of your application interacts with. The templates are a combination of HTML and data from the database.

bin – It contains Rails scripts that starts your application. It can also include other scripts that you use to set up and upgrade the application.

Config – This holds configuration files - database.yml, environment.rb, routes.rb, etc. that your application needs to run.

DB – This directory contains files/scripts that are used to manage your application database.

lib – This directory contains an extended module for your application.

log – This contains log files - server.log, development.log, test.log, and production.log, etc., that are used for debugging or monitoring your application.

public - This directory contains static files and compiled assets, such as HTML files, Javascript files, images, and stylesheets.

test – This directory holds test files you write to test your application functionality.

tmp – This directory contains temporary files like cache and pid files.

vendor – This directory contains third-party libraries.

Gemfile – This file specifies what your basic gem requirements are to run your web application. You can group the gems into development, test or production and Rails will know when to include each gem.

Gemfile.lock – Unlike the Gemfile that explicitly lists the gems you want in your application, Gemfile.lock additionally contains other gems that those you list in the Gemfile depends on that are then automatically installed to satisfy the dependencies.

Readme.md – You use this file to share essential detail about your application, such as what the app does, how to go about installing and run the application.

Rakefile – This file contains various rake tasks definitions, which helps in automating everyday administration tasks of your application.

config.ru – This is a Rack configuration file that provides an interface to the webserver to start your application.

Change directory to the 'todo_app' directory Rails generated and run 'rails server' to start the application. Type localhost:3000 in the address bar of your web browser, you should see the Figure below if all went well.

This is the default homepage of your application, and you will change this in the later section of the tutorial. You can stop the server by pressing 'Ctrl-C'.

Rails – Generate commands

The Rails generate command makes use of templates to create a whole lot of useful things in your application. You can use these generators to save a lot of time.

It helps by writing boilerplate code, code that is necessary for your web application to work. You can run 'rails generate' by itself at the command prompt or Terminal to see a list of available generators as shown below:

You can also run 'rails generate "command"' to see a description of what the command does. It offers convenient options that can abe run with the command and usage example. The Figure below shows the output of running' rails generate controller':

You will use the rails generate scaffold command to automatically create the model, view, and controller for the todo list application you are building. Run' rails generate scaffold todo_list title:string description: text' in your Terminal (check you are still in the todo_app directory).

This will create a full CRUD (Create, read, update, and delete) web interface for the TodoLists table.

Another useful command to know is 'rails destroy,' it reverses whatever 'rails generate…' does.

Rails – routing

The Rails routing system, rails router, handles all incoming requests to your web application. It does this by examining the URL of the incoming requests and then maps each request to the controller action responsible for handling it, using special syntax specified in the routes file (config/routes.rb).

The routes file helps in controlling every URL aspect of your web application. Rails by default use a RESTful design based on the REST architectural style, that provides a mapping between HTTP verbs and requests (URLs) to controller actions.

The routes file was generated when you ran 'rails new' in an earlier section of this tutorial. Continuing with the Todo application that you are building, run the following' rails db:migrate' (you will get to know what this does shortly)

In your command line, make sure you are still at the root of the application (the todo_app directory).

Then start the server again with 'rails server'. Type http://localhost:3000/todo_lists/ in your browser and press Enter. You should get back a webpage as shown in the Figure below:

This is the Todo lists view that the scaffold command generated and it is controlled by the TodoListsController's index action.

Go ahead and add a todo list by clicking on the 'New Todo List' on the page, you should get the page as shown below:

Notice the URL is changed to http://localhost:3000/todo_lists/new . This is the page to create a new todo list, and it is controlled by the TodoListsController's new method/action.

Enter your todo list title and description in the form and click the Create Todo list button, the URL should change to http://localhost:3000/todo_lists/1, shown in the Figure below:

This is the show page of a todo list, and it is controlled by the TodoListsController's show method/action. If you go back to http://localhost:3000/todo_lists/, you should now see the Figure below with a new todo list added:

Rails was able to map the various requests (URLs) to the corresponding TodoListsController's action using the route definition in config/routes.rb.

If you take a peek at this file, you see a single line 'resources: todo_lists', is Rails default way of writing restful routes. This single line creates seven routes all mapping to the TodoLists controller.

By convention, each controller's action also maps to a specific CRUD (Create, Read, Update, and Delete) operation in the database.

You can run 'rake routes' in your command line to see the various routes available in your application. The Figure below shows the output of running 'rails routes' in your command line/terminal.

Rails – views

The View layer is one of the components of the MVC paradigm and is responsible for generating HTML response for each request to your application. Rails by default use ERB (Embedded Ruby) which is a powerful templating system for Ruby.

ERB makes writing templates easy and maintainable by combining plain text with Ruby code for variable substitution and flow control. An ERB template has .html, .erb or .erb extension.

You will mostly use a combination of two tag markers only, each of which causes the embedded code to be processed and handled in a particular way.

A tag with an equal's sign '<%= %>' indicates that embedded code is an expression and that the result of the code should be substituted by the renderer when it renders the template.

The other tag with no equals sign '<% %>' indicates to the renderer that the result of the code should not be substituted/printed when it renders the template.

Each controller in your Rails application has a corresponding subdirectory in app/views, and each action/method in a controller has a corresponding .html and .erb file in this directory.

Take a look at app/views of the todo app you are building. You will find a subdirectory named 'todo_lists' inside this subdirectory .html.erb files with names corresponding to the actions/methods in the TodoLists controller.

Rails – ActiveRecord, active record pattern, and orm

ActiveRecord is the Ruby implementation of the Active Record pattern, which is a simple pattern where a class represents a table, and an instance of the class represents a row in that class.

ActiveRecord is popularly referred to as an ORM (Object Relational Mapping), a technique that allows you to manage your database using a language you're most comfortable with. It is database agnostic thus you can easily switch between databases (for example SQLite, MySQL, PostgreSQL, SQL Server, Oracle, etc.). This suite more for your application requirement with the same code/logic.

So, if you want to get an array containing a listing of all the todo lists in your application, so, instead of writing code to initiate a connection to the database, then doing some sort of SQL SELECT query, and converting those results into an array.

For that, you just need to type 'TodoList.all' and Active Record gives you the array filled with TodoList objects that you can play with as you like.

All you need do is set up the right configuration in config/database.yml, and Active Record will work out all the differences between the various database system.So when you switch from one to the other, you don't have to think about it.

You focus on writing code for your application, and Active Record will think about the low-level details of connecting you to your database. Active Record makes use of naming conventions to create the mapping between models and database tables.

Rails pluralize your model class names to find the corresponding database table. So, for a class TodoList, ActiveRecord will create a database table called TodoLists.

Rails - Migrations

Rails migration is simply a script that you use to edit your application database. It is used to set up or change your database and avoids manually writing SQL code to do that.

It uses Ruby to define changes to database schema and makes it possible to use version control to keep your database synchronized.

Rails Migrations use a Ruby Domain Specific Language (DSL). This acts as an abstraction and makes it possible to use or change your database engine based on your requirements.

They can be shared with anyone working on the application and can also be rolled back to undo any changes to the database. This is a high safety mechanism as you don't have to bother about doing permanent damage to your database.

Rails - ActiveRecord Associations

A connection between two ActiveRecord models is known as an association. Association makes it much easier to perform operations on the different records in your code. It can be divided into four categories: -

One to One: - This indicates that a record contains precisely one instance of another model. A good example is user profile. A user has only one profile. It uses has _one keyword.

One to Many: - This is the most common association, and it indicates that one model has zero or more instances of another model. Your use has a _many keyword to denote this association.

Many to Many: - This association is a bit more complicated, and ActiveRecord provides two ways to handle it. Using the has_and_belongs_to_many and has_many, which gives you access to the relation that is defined in a separate table.

Polymorphic One to Many:- This is a more advanced association available to you in Rails. You can use it to define a model that may belong to many different models on a single association.

Rails - ActiveRecord Validations

Validation helps to ensure that you have correct data because working with wrong data is an awful thing and could cost you your money and business.

Validation also provides an extra layer of security for your application against malicious users from gaining access to information in your database. Rails offer you a nice API of validation helpers in ActiveRecord to keep your database clean, secure, and free of errors.

ActiveRecord validations run on model objects before saving to the database, making them more reliable and also best practice to follow in building your application.

The following ActiveRecord methods evoke validations when used or called on model objects - create, create!, save, save!, update, and update!. The ones with a bang (create!, save! and update!) raise an exception if a record is invalid while thothen't'tt't't.

The most common ActiveRecord validation helpers at your disposal are:-

Confirmation:- This validation helper is useful for validating two fields have the same entry. e.g., password and password confirmation, it is used in conjunction with the presence validation helper.

Presence:- This checks that the field is not empty.

uniqueness: ensures unique value for a field, e.g., username

Length:- To enforce a limit on character length of a field

You can also create your custom validation by using the validate method and passing it the name of the custom validation method.

You can check the model's error object to find out why a validation. Hopefully, you have some ideas to make your application more constrained and more secured to only allow secure data into your database.

Rails - ActionController

The Rails controller is the center of your web application. It facilitates and coordinates the communication between the user, the models, and the views.

Your controller classes inherit from the ApplicationController, that contains code that can be run in all other controllers and it inherits from ActionController class.

The controller provides the following to your application:

  • It routes external requests to internal actions
  • It manages to cache, giving performance boosts to your application
  • It manages helper methods that extend view templates capabilities. It also manages user sessions, giving them a smooth experience using your app.

Rails - Configurations

You can configure the various components such as initializers, assets, generators, middlewares, etc. By using your Rails application initializers and configuration files in the config directory. Files like config/application.rb, config/environments/development.rb and config/environments/test.rb etc. You can also have custom settings configure for your application.

Rails - Debugging

As you build out your application, there will come a time you will need/have to debug your code. Rails make this easy using the byebug gem. You can start a debugging session by putting the 'byebeg' keyword anywhere in your application code.

This will temporarily stop execution at that point. The byebug gem gives you several commands to use. The most useful ones are:

  • next: command that enables you to go to the next line of code, skipping all methods invoked by the execution of the current line.
  • step: this is similar to 'next' command but will make you step into each invoked.
  • break: this stops the code execution.
  • continue continues execution code.

There are other debugging gems available such as 'pry', and they all provide similar functionalities but slightly different syntax. Debugging gems should not be used in production as this pose's risks to your application and bad experience to your application users.

There are log files that you can inspect for errors in production and handle them. Also, you should follow a TDD (Test-driven development) approach when developing your application to ensure everything works well before deploying to production.

Summary:

  • Ruby is a pure object-oriented programming language
  • Ruby has an elegant syntax that is both easy to read and write.
  • Rails is a development framework, written in Ruby, for building web applications
  • The installation process will depend on your operating system.
  • Rails is packaged as a Ruby gem, and you can use it to build a variety of applications.
  • You will create a Todo list application in this tutorial, run the followincomm'n'n' 'rails netoda'p'p'p' in youR Terminal to create the application.
  • The Rails generate command makes use of templates to create a whole lot of useful things in your application.
  • The Rails routing system, rails router helps you to handles all incoming requests to your web application.
  • The View layer is one of the components of the MVC paradigm and is responsible for generating HTML response for each request to your application.
  • ActiveRecord is the Ruby implementation of the Active Record pattern.
  • Rails migration is simply a script that you use to edit your application database.
  • A connection between two ActiveRecord models is known as an association.
  • Validation helps to ensure that you have correct data because working with wrong data is an awful thing and could cost you your money and business.
  • The Rails controller helps you to facilitates and coordinates the communication between the user, the models, and the views.
  • Rail helps you to configure the various components such as initializers, assets, generators, middlewares, etc.

 

YOU MIGHT LIKE: