Table of contents
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.
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.
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.
The components of an MVC can be broken down into the following-
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 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-
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.
Routes indicate URLs that will direct applications and determine which part of the code should manage related requests.
4. 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.
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.
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-
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.
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-
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-
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.
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-
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.
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
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
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.
(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.
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.
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.
(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.
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-
You will notice various environments assigned because of Rails 3 modes. These are:
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.
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.
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-
Generate the model with the fields using the model generator-
Now, open the migration file
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.
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-
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-
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-
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-
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-
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.
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!
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.
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.
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-
Discovering the sequence will make the comparison of numbers to find the one that is missing easier.
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.
Use the regular expression here with the match? Method. See the code example below-
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-
The example can also be solved by using a stack-
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.
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-
The code will find out the most extended and repeated character with the string given.
You mustn’t confuse this with the Law of Demeter because the law deals with reaching into other objects’ internals.
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-
For this example, you must delete the last character on spotting the # symbol.
The article has covered a set of examples, along with necessary explanations. Hire ruby on rails developers who will help 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!
Step into a new land of opportunities and unearth the benefits of digital transformation.