All you need to know about getting started with Ruby on Rails

In this blog, we explore the inside-out of getting started with Ruby on Rails. Starting with the basics of Ruby, we explore various uses and components of the language. Thereafter we go on to describe the step-by-step process of getting started with Ruby, how to use it and explore some Ruby code examples before ending it. Read in detail.
All you need to know about getting started with Ruby on Rails

Ruby is a programming language that was created by Yukihiro Matsumoto and released in 1995. The language is carefully balanced and known to take massive inspiration from its creator’s favorite languages like Eiffel, Smalltalk, etc. If you think the language is dead and isn’t as popular as it was in 2006, let us tell you that it is on the 8th spot in the recent rankings list published by RedMonk.

Its coding style is simple and almost 30-40% faster than in contemporary technologies, making it a perfect fit for a start-up. This time reduction subsequently helps companies save up on a lot of money! This article will help you explore the basics and provide you with some resources to make your job easy when using Ruby. So, call it your user manual concerning Ruby.

Understanding the Ruby basics

Understanding-the-Ruby-basics
Some Ruby Basic that will help a new programmer in getting started are mentioned below-

  • Ruby is open-sourced, and you can download it online without much hassle. Keep in mind that the costs are subjected to a license.
  • Ruby takes its inspiration from other languages like Lisp, Ada, Perl, and Basic.
  • It is a general-purpose programming language that is object-oriented.
  • You can use it to create intranet and internet applications.
  • Ruby is an interpreted language.
  • It is utilized to write the common gateway interface or CGI scripts.
  • Ruby’s syntax shares similarities with the likes of Perl and C++, which are popular programming languages.
  • You can install it on Windows and POSIX environments.
  • It supports GUI tools like OpenGL, GTK, and Tcl/Tk.
  • It possesses in-built functions that can be used right away into Ruby scripts.
  • It can easily connect to MySQL, Oracle, Sybase, and DB2.

Ruby: High-level programming language

Ruby is popularly called ‘programmer’s best friend’ because reading the Ruby code can be compared to reading a book. It means Getting Started with Ruby will be more comfortable as compared to other programming languages. Ruby hides a lot from the programmer, which ensures the project completes quickly.

It is dynamically typed and is known to support various programming paradigms that include object orientation, procedural and functional programming. Ruby was used to build the Ruby on Rails framework and was used in writing code for the popular software package installing tool macOS. The language was used to create the well-known Metasploit website, security software that helps test apps and websites.

How does Ruby work?

How ruby works

Ruby gained widespread popularity for being the coding language used in the Ruby on Rails framework. To understand How Does Ruby Work, you must gain an understanding of the Ruby on Rails Architecture.

The architectural pattern utilized by Ruby on Rails is called Model View Controller or MVC. This architecture type is known to increase the performance and being the structuring basis of web applications.

The MVC architecture follows the convention over configuration rule, commonly known as the “Coding by Convention”. So, you don’t need to worry about making decisions until you follow ROR conventions.

MVC

The components of an MVC can be broken down into the following-

  • Models – stored within a database and handle all interactions within it. They also indicate data in the database and carry out accurate verifications.
  • View – plays the role of maintaining the view display logic and will specify the user interface. The view in most HTML files in a ROR has the Ruby code. The code enclosed is uncomplicated because it has conditionals and loops.
  • Controller – responsible for handling the flow of an application. It communicates with models and views and then processes the requests coming from browsers. They also process the data from models and send them to views for presentation.

ROR-cta-first
The MVC architecture, followed by Ruby on Rails, has six essential components. These are

1. Models

They are the main component of the business and represent the business domain in the Ruby language. It will act as the interface to initiate storage in ROR frameworks. Models provide methods that ensure movement of the model case’s memory-resident state is possible within the database.

Example- ‘order.save’ could store order representation in related database tables.

Models in the MVC architecture aren’t web apps but can carry out multiple functions using Models only. So, if the rails console session was started, then accessing models of their apps could execute some work with data management.

2. Ruby on Rails Server

Ruby on Rails Server

Ruby on Rails server portrays a web server that is executable and can be used to request the browser. This is because it stays on port and IP. As the development is initiated, the Rails server will begin to receive requests on the local system on post 3000. It gives you a web address- http://0.0.0.0:3000/

The Rails server utilizes MVC architecture to receive offers and assign the processing to various components that make it. This server will also help in the writing of logs in the log folder.

3. Routes

Routes indicate URLs that will direct applications and determine which part of the code should manage related requests.

4. Controllers and their actions

Controllers and their actions

Controllers are responsible for managing a request by using any of its actions. Controllers in Ruby class and its actions exist as public methods. The actions create data that can be used in HTML sent back, which is a reaction to the HTTP request.

This response is performed by utilizing models and gaining data from the database or executing domain-oriented operations and calculations.

The objects are used by view using an HTML rendering technique, making sure a continuous request handling cycle is followed.

5. Views

Views are responsible for informing Rails regarding the content of HTML that is sent back to the browser by request. The Views in an MVC architecture rely on data produced by the controller. This data usually needs a layout that is part of the HTML markup, and the view is present within it.

So, there may be multiple views using a similar layout. The layout holds content familiar with numerous views and, in general, contains views content.

6. Assets

They are essentially Javascript code, CSS code, or different media style images. A view text present in the layout gets conveyed to the browser, which has requested a page. The assets will be sent along with the views to the browser.

What does Ruby do?

Ruby

Are you wondering What Does Ruby Do? Then let us tell you that Ruby is a language meant for general-purpose programming and generally used for web development projects. It ensures the data is stored even when the user is done browsing the page or closed it. After this, Ruby will continue to update, create, retrieve, and keep that data into a database.

For instance, if you wanted to create a web app like twitter that stores all the tweets written on it in a central database. All your tweets will still be accessible just as you left them, even if you exit the browser or shut the computer.

Ruby offers another feature that helps others locate you by simply typing a keyword in the tweets. Typing out the keyword sends a query to the Central Database to display any matches.

A Ruby developer can execute duties like information storage in the database. The Ruby framework Rails can accelerate development by adding templates, pre-built codes, and other ways that make performing these tasks easy. Thus, websites tend to employ the Rails at the same time.

Apart from twitter, other websites that have attained success by using Ruby on Rails are-

Some Ruby projects that must be mentioned here are-

  • Homebrew that is present on macOS and acts as the missing package manager
  • Metasploit, a widely used penetration testing framework
  • Sinatra helps in the creation of web apps in Ruby
  • Rails is one of the most famous frameworks associated with Ruby

These examples tell you that Ruby, combined with the Rails framework, can be used to make a variety of website applications. Rails will emphasize more on the productivity that makes individual developers write code and test prototypes quickly. The framework is also suitable for handling unlimited users every month regardless of the language being used.

How to use Ruby?

How to use ruby

Most developers are jumping on board the Ruby rail because of the framework Ruby on Rails. The Ruby language is impressive once you have nailed the Ruby Basics, but that does not mean that the language limits itself to what Rails can do because it is a general programming language.

So, you can use it to make pretty much anything, even medicine, and biology.

The language can be used for creating practical things like-

  • Servers
  • API clients
  • Command-line media player and other command-line tools
  • Data cleaning, filtering, and parsing
  • Static website generation
  • Crawling and web scraping
  • DevOps, Backup and automation tools
  • Development of full-stack websites
  • Reporting generators for PDF, CSV or HTML

Some less practical usage examples are-

Keep in mind that other projects, too, can be created using it but will require more effort and domain and code knowledge. A list of links mentioned below will help you in further understanding the capabilities of Ruby-

Getting started with Ruby

Now that all the necessary details regarding Ruby have been provided, let us talk about how you can get started with the tutorial. The tutorial will focus on helping you in the creation and writing code for a web app.

Step 1- Installation of Ruby on Rails to Linux Server

Installation of Ruby on Rails to Linux Server

The first step in creating an app is installing the Ruby on Rails framework on a compatible system. This installation process was initially considered to be tediously complicated. However, it can be simplified by making a SkySilk ruby account on Rails VPS.

Start by logging into your SkySilk dashboard; if you don’t already have an account, then you can make one by clicking on this link-
https://www.skysilk.com/login?redirect=/dashboard/images/new

Once you have logged in, then select a plan of choice, choose a hardware configuration. You can also configure custom hardware! After the hardware configuration, click on “Apps and Tools” and then search for “Ruby on Rails” and click on it. Now all you must do is fill out the required information and then click on “Go”

And then the installation process is complete.

Step 2- Creation of a new directory

An SSH or secure shell is a mandatory addition to the brand-new container once the setup for Ruby on Rails is done. This step is vital for all those who have recently created servers using SkySilk. The instructions apply to machines that have the “Password Disallowed” option enabled.

A Brief note on SSH and its importance- A secure shell will help create an encrypted tunnel that runs between the computer/any smart device and a remote machine that is being used for command-line login.

Creating VPS sans SSH by using password login
Creating-VPS-sans-SSH-by-using-password-login
SSH KeyGen is usually suggested but you can also bypass the process. SkySilk provides the option to make a VPS without generating the SSH key by using the password only when needed. For this to work, the password must be very secure, so hackers or unwanted persons do not gain it.

A virtual server can be created by deploying a new container from the VPS dashboard and then click on “Password Allowed.” You will have to set up the password and then click on GO.

Setting SSH key pair
Setting-SSH-key-pair
The setting up process for the virtual machine will ask you to give a public SSH setting up key. This key will be a hashed key that Linux VPS compares with newer incoming connections. If you have previously created a machine using this method before, select the once used PuTTY SSH key from the drop-down menu.
image 1
(Picture courtesy- https://rb.gy/bqhyrd )

If you haven’t, then you must create a public key pair for the new VPS.
image 2
(Picture courtesy- https://rb.gy/bqhyrd )

You will successfully log into your Linux VPS after generating the public key, saving the private access to your computer, and attaching the public key to the server.

Connecting VPS via SSH, for Mac OS X and Linux

If connecting from a Unix like a machine, then use the connect command- ssh [user] @[ip address]
In this command, the [user] will be your user name, and the [ip address] specifies one of the virtual machines.
ROR-cta-second
Connecting VPS using SSH, for windows

Windows users will require a third-party program for connecting to the server. Click- to download the PuTTY program. It is the popularly used one for SSH connections. Once your connection with PuTTY SSH is successful, then specify your private key for authentication.

On expanding the SSH menu of your connection settings and then selecting the Auth menu will help you put down the private key.
image 3
(Picture courtesy- https://rb.gy/bqhyrd )

As you see in the picture above, click on the Browse key and then go to where you saved your private key on the computer. Load the key and then navigate back to the session menu.
image 4
(Picture courtesy- https://rb.gy/bqhyrd )

Keynote- make sure the SSH is selected, and the port is 22. Now fill in your IP address of the VPS and then click it open.

A new window opening will signify you have managed to connect to the machine successfully. After this, you will have to install the database support, use code below- sudo apt-get install sqlite3 sqlite3-devel

The SQLite is a lightweight database that is popular and supported by Rails.

Step 3- Creating the Ruby on Rails web app.

The app generation on Ruby Starts with the creation of a base application structure. You must head out to the directory and run it as you see in the image below-
image 29

Here the Rails default is based on the SQLite, and the command is a generator. What does it do? It copies all stored files into a new directory and by default creates a sqlite3 database within /bookshelf/db/development.sqlite3, and /bookshelf/db/testing.sqlite3. Information regarding the database connection gets deposited in /bookshelf/config/database.yml.
Your file will look something like the code in the image below-
image 5
You will notice various environments assigned because of Rails 3 modes. These are:

  • Development
  • Production
  • Testing

Each of these modes has a different database and setting. The development is a default environment. Now you have to start a server for the app by using the /script/server command.
image 6
You can visit your app by pointing the browser to your container’s IP address and seeing the splash page. Since the code functions on a fundamental level, you need to delete the splash page and start coding.
image 7

Step 4- Models, Controllers, and View

The application now needs data that will be supplied by models, and this step educates you on how to generate them. Rails already possess generators for everyday tasks, the file/script/generate code signifies it. This generator creates the model.rb file and adds a migration file to add the table to a database.

Why is a migration file necessary? Because it has a code that helps in the add/drop of tables and also alters/remove/add columns from these tables. They are usually executed in a sequence to make a table. You will have to use ‘rake,’ a ruby code runner, and other commands to run a migration.

Two attributes must be kept in mind when creating a book, they will be sufficient for starting the app-

  • Title- String
  • Thoughts- Text

Generate the model with the fields using the model generator-
image 8
Now, open the migration file
image 9
The columns created in the create_table: books block, and automatically, a primary id key created. Columns added using t.timestamps for updated_at and created_at. To run the migration, you have to use the db:migrate rake task, it applied to the pending migrations.
image 10
Since there is a table available, a dummy book can be created and is done using IRB on the console. It also loads all projects to the classes.

You can open the Rails console like what you see below-

image 11
It is time to put the books required for that controller in the system on display. The scenario will correspond with the index action in the BooksController or books_controller.rb. Follow the coding below to understand how to create the controller-
image 12
The action that displays and locates all the books must be defined. It is performed using the previously created Books.all and assigning it to the instance variable must be done. Instances and variables are assigned so the views can render with the controller binding.

The views possess the ability to access the variables defined in the actions, but only, for instance, variables. By performing this action, the instance variable scoped to object instead of the action. Follow the code below to understand how-
image 13
The controller will help find all the books! To tie it to the URL, some routes must be created.

The Rails already possess handy functions that can generate RESTful routes, which will produce URLs like /makes/1 and /makes. They will be combined with HTTP verbs to find out the best method for calling the controller in.

The map.resource can create RESTful routes. Now open /config/routes.rb and change it to what you see in the image below-
image 14
Here Routes.rb may seem mysterious to new users, but running routes rake tasks that display all the routing details will make it easy. See image below-
image 15
Now create a new file by the name of /app/views/books/index.html.erb copy what you see below. It will help in making a template that displays all books.
image 16
There are simple loops all over @books, and each book displays some HTML. You may be able to notice a subtle difference. <= used when an output of a text is needed and. <% used when it isn’t. The h before the book.title. h shows a method that breaks free from HTML entities. The h text translates to: h(text). Now you can run the server and see what you have managed to create!

For that, you are required to start the server, visit link- http://YOUR-IP-ADDRESS/books.
image 17
If the code is executed correctly, then you will be able to see some basic HTML.

Exploring some Ruby code examples

The compilation of 7 Ruby Code Examples in this subheading will surely help gather Ruby patterns, methods, and tricks.

Sum of 2 numbers

The example aims at finding a combination of 2 numbers from a range of unique numbers. These, in addition, produce a targeted number.
image 18
Here the product method will be used. Using this method will be like having a loop within a loop that merges all the array A values with values in array B.

Counting, Finding, and Mapping

If you want to discover the missing numbers in the arithmetic sequence, for example (2,4,6,10). The strategy applied here must calculate a difference between numbers.
image 19
The goal is to discover the sequence, does it increase or does it decrease and by how much!
The code you see below discloses the sequence-
image 20
Discovering the sequence will make the comparison of numbers to find the one that is missing easier.
image 21
Regular Expression Example

If working with the strings and you wish to find out the patterns, then you’d best use the regular expressions.

This example will require the uncovering of a given string. It follows the pattern of VOWEL to NON-VOWEL characters, as you see below.
image 22
Use the regular expression here with the match? Method. See the code example below-

image 23
Noteworthy things

  • The cycle method used here helps in switching from VOWEL regex and NON-VOWEL regex.
  • The strings are converted into an array of characters with chars to utilize them all? method.

Recursion and Stack example

Recursion happens when the method calls itself numerous times to advance towards a solution. It can solve many problems using it, but it comes with its limits, and you could use a stack data structure that could be used as a replacement.

The example here aims at finding out the Power Set of the given array. A Power Set is created from the array and is the set of all subsets. See the example with Recursion below-
image 24
The example can also be solved by using a stack-
image 25
At each pass of the employed algorithm, either a number is taken or not taken. To show you the possible combinations, both outcomes have been displayed.

Noteworthy things-

  • The recursion solution was much shorter.
  • The making process parts of the algorithms (index+1) are pretty much the same.
  • The stack used is an array as Ruby is not a Stack class.

ROR-cta-third

Method Chaining Example

This example perfectly shows the power exuded by Ruby. The combining methods ensure you can take the produced output through one method and then pass it to another. With just a few raw materials or input, you can steadily change them into results you want. See the example below-
image 26
The code will find out the most extended and repeated character with the string given.

Noteworthy things-

  • The code has been formatted to increase readability
  • Using the Symbol#to_proc pattern (&:size)

You mustn’t confuse this with the Law of Demeter because the law deals with reaching into other objects’ internals.

With Index Example

The with_index method is used if you want to have the current index when iterating a collection of items. See the example below-
image 27

Noteworthy things

  • The with_index and even? Are combined to find out the presence of the reverse of the current word.
  • Gsub, in the absence of a block, gives back an Enumerator object. It makes sure you can chain Gsub with other methods as well.

Each with Object Example

each_with_object and the with_object are exciting methods as well. Use them when you want the object to hold results. See the example below-
image 28
For this example, you must delete the last character on spotting the # symbol.

Noteworthy things

  • The each_with_object will take the argument regarding the object you wish to start with and make it the second block parameter.
  • The string is converted into an array of characters (char) and then into a string once (join) is done.
  • A ternary operator is used to decide on what to do that makes a code shorter.

Conclusion

The article has covered a set of examples, along with necessary explanations. These will have helped you understand Ruby’s inner workings and its framework, the Ruby on Rails. Ruby is a delight for any programmer and will help create a range of websites and make sure they reach their highest potential in a short period. GOOD LUCK, programmers!

Harikrishna Kundariya
Harikrishna Kundariya
Harikrishna Kundariya, a marketer, developer, app lover, technology savvy, designer, co-founder, Director of eSparkBiz @Mobile App Development Company where you can Hire Mobile App Developer. His 8+ experience enables him to provide digital solutions to new start-ups based on app development.

Related Post

Analyzing The Best Ruby Frameworks For Developers
  • RoR
  • September 26, 2020

Analyzing The Best Ruby Frameworks For Developers

Ruby on Rails is an open-source web framework, that's written in the Ruby ...

Analyzing the Best Ruby on Rails Gems in Detail

Analyzing the Best Ruby on Rails Gems in Detail

Ruby on Rails is an open-source web framework, which is written in the Rub...

Ruby on Rails vs PHP: Which One Suits Better For Your Business?
  • RoR
  • September 5, 2020

Ruby on Rails vs PHP: Which One Suits Better For Your Business?

Ruby on Rails and PHP are amongst the two most widely used ways of develop...

Guaranteed Response within One Business Day!
person We are always looking to partner with great people & incredible brands, so let’s connect.