Skip to main content Link Search Menu Expand Document (external link)

Ruby on Rails introduction

Table of contents

  1. What is a Web framework?
    1. ORM
    2. URL Routing
  2. What is Ruby on Rails?
  3. Why Choose Rails?
  4. What Rails is Not
  5. What is Ruby?
  6. Benefits of Dynamic Programming Languages
  7. Why Choose Ruby?

“Life’s too short to build something nobody wants” - Ash Maurya, Running Lean: Iterate from Plan A to a Plan That Works

Ruby on Rails is a server-side web application framework which is high productive, maintainable and easy to deploy. From obscuring to world famous, let’s find out the reason why makes Ruby on Rails special.

What is a Web framework?

Since Tim Berners-Lee invented the World Wide Web in 1990, there already have a strong demands for dynamic web page developers, also known as website developers, from market of talents. The most popular method is to use Perl CGI at early times, we will input HTML form in Perl and take one simple counter as an example.

   #!/usr/bin/perl
   open(FILE, "count.txt");
   $num = <FILE>; $num++;
   close (FILE);
   
   open(WRITETO, ">count.txt");
   print WRITETO "$num";
   close (WRITETO);
   
   print <<PRINTAREA;
   content-type:text/html\n\n
   <style>
   <!--
   body {background-color: black; line-height:1;
   margin-top: 0cm;
   margin-left: 0cm;
   margin-right: 0cm}
   -->
   </style>
   <body><center>
   <b><font size=1 color=white>
   $num</font></b>
   PRINTAREA

In this scenario, you could discover that it is hard to read and maintain when the HTML form is taken the major part of the code. Around 20th century, PHP, ASP and some other programing languages based on Template system are prevalent, along with relational databases like MySQL. This approach is exactly the opposite of Perl CGI that we mentioned above, which the program and SQL orders are actually embedded within the HTML template. The following code is a PHP & MySQL program, and the part enclosed in <?php … ?> is the PHP program:

   <?php
     $db = mysql_connect("localhost", "root", "password");
     mysql_query("SET NAMES 'utf8'");
     mysql_select_db($SERVER['db']);
   ?>
   <html>
     <?php
       $sql="select * from news where Class='1' or Class='3' order by CTDate desc limit 0,5";
       $result= mysql_query($sql);
       while ( $arr=mysql_fetch_array($result) ) {
         echo <<<NEWSEND
           <div class="box">
             <span class="box-title-1"> <b>【$arr[Title]】</b> $arr[CTDate] </span>
             <div class="box-content">
               $arr[Text]
             </div>
           </div>
         NEWSEND;
       } 
     ?>
   </html>

In this manner, you could comprehend PHP&MySQL is much easier to use especially in system like discussion, blog, content management system(CMS), Wiki. It mainly focuses on the aspects for preservation and displaying of the data, so it’s particularly suitable for the development which does not require complicated business logic. Understanding Programs are only the interface of database management systems. Neither following model-view-controller (MVC) pattern, separating the page and the logic, nor supporting Object-oriented programming (OOP) paradigm, we could still undergo the development well by using PHP&MySQL.

However, with the trending for Web 2.0 and cloud computing bringing more demands for web application development, web application scales up and requires abundant business logics and features. This development approach causes the structure of projects becoming extremely complex and makes team development become difficult. Maintaining such a website can be challenging because the business logic is mixed with the HTML, making it difficult to understand and modify. Not to mention that different developers may have different program architectures, and the lack of technical documentation by inadvertence might makes it much harder to conduct a testing as well.

Thus, we have the need for a web framework, which completed complete object-oriented concepts and techniques. And the so-called framework is a set of specifications and conventions that are firstly established to enable developers to develop within this framework.

Wikipedia defines “software framework” as a set of software component specifications that are designed to achieve an industry standard or complete a certain basic task. It also refers to software products that provide the basic functionality requiring to implement a software component specification. The functionality of a framework is similar to infrastructure and is independent of software applications. It provides and implements the most basic software architecture and system. Software developers typically achieve complex business purposes and logic based on specific frameworks, and applications can also run under a software system which supports the same type of framework.

A Software Architectural Patterns called MVC has been put into practice by many of the web frameworks, which divides software into 3 parts:

  • The Model object packages data and business logic, such as database manipulation.
  • The View represents the user interface, displaying and editing forms. We may use embedded Ruby in tags mingled with HTML.
  • The Controller interacts with the Model sending and receiving data, handling incoming HTTP requests from the outside world (i.e., the browser), interacting with the Model, and outputting the View (i.e., HTML).

The steps illustrated in this diagram are:

  • The browser sends an HTTP request
  • The Controller handles the request and interacts with the Model
  • The Model accesses the database to retrieve data
  • The Controller feeds the obtained data to the View template
  • The final HTML document is returned to the browser

Through the MVC pattern, we can organize our code systematically, separate business logic from the user interface, allow frontend and backend developers to work independently, and make our code a consistent structure in clear file locations. These conventions are usually provided by web frameworks. With coding standards being established, development and maintenance become much easier.

There are also some simple web frameworks that do not follow the MVC pattern. It usually called micro-frameworks, and Sinatra is a good example. We will briefly introduce this web framework in other chapter.

There are some differences between Web application MVC and desktop application MVC, mainly because the View in Web application MVC cannot be updated through the Observer pattern. Interested readers can refer to the article “Model View Controller: History, theory, and usage” for more information.

Web frameworks usually include the following features:

ORM

ORM (Object-relational mapping) allows us to manipulate relational databases using object-oriented syntax, making coding much more efficient and easy to use. It eliminates the need for writing tedious SQL syntax, and increasing code maintainability. For example:

SELECT * FROM orders, users WHERE orders.user_id = users.id AND orders.status = "Paid" LIMIT 5 ORDER BY orders.created_at;

In Rails, the equivalent syntax would be:

Order.where(:status => "paid").includes(:user).limit(5).order("created_at")

URL Routing

If we map URLs with directory structure for the PHP project and the URL is /foo/bar, there must be a file named bar.php under the /foo directory. This one-to-one mapping may be intuitive but it greatly restricts program architecture and development. Therefore, URLs in PHP often become less pretty and not conducive to SEO (Search Engine Optimization).

And this problem could be solved by using web frameworks for its flexibility. You can create any URL for an action method of a controller, regardless of the file location.

Web frameworks provide developers with lots of libraries for developing web applications, such as Templates, Email, Session, Caching, JavaScript/Ajax, testing. In addition, most of the features that we use for developing web applications are built-in, so we don’t need to reinvent the wheel.

What is Ruby on Rails?

Ruby on Rails (officially abbreviated as Rails, and unofficially as RoR) is a web framework developed in Ruby, an open-source (under the MIT License), object-oriented scripting language. It is primarily used for developing database-backed web applications. Rails is a professional framework that follows the Model-View-Control (MVC) pattern and offers built-in mechanisms for unit testing and integration testing. Moreover, it supports Ajax and RESTful interfaces, ORM mechanisms, and supports latest industry standards such as HTML5 and jQuery. Its creator, David Heinemeier Hanson (DHH), separated Rails from 37signals’ commercial applications and made it an open-source project in 2004.

Rails was designed to make web development much easier for developers who are familiar with its conventions. Comparing to other programming languages and frameworks, Rails allows you to achieve more functionalities with less code, and even makes web development more fun.

Rails’ philosophy includes the following guiding principles:

  • Don’t Repeat Yourself (DRY) - writing repetitive code is not a good thing.
  • Convention over Configuration - Rails presets all kinds of practical settings and conventions, and it works as expected without having to write configuration files.
  • REST is the best pattern for web applications - using Resources and standard HTTP verbs to organize your application is the fastest way (we will discuss this powerful design in the other chapter).

Why Choose Rails?

In the current era of website development using frameworks, Those who are familiar with frameworks can quickly complete tasks and understand the structure of website programming. Getting started with various programming languages is not too difficult. In author’s opinion, the essential is that if you could deeply understand the framework of the tool which you used.

Therefore, regardless of programming language preferences, Ruby on Rails is currently the most successful and technologically advanced front-end web server among other web frameworks. Its concepts have deeply influenced many following web frameworks for other programming languages, ASP.NET MVC, CakePHP, Grails, TurboGears, Pylons, web2py, catalyst, etc. We could efficiently develop website applications by using clean and concise code. Furthermore, what may surprise you is its vibrant and diverse community comparing to other web frameworks based on the current dynamic programming languages. Rails community is full of rich collections of related books, seminars, consulting firms, third-party services, plug-ins, etc. Since there are many Rails users, people have provided best practices for development in all aspects, such as how to write clean code, security and performance for the website, scalability, full-text search, asynchronous processing.

And without a doubt, the most crucial point is the productivity would be dramatically enhanced for it becoming much easier to write new applications and add new features. It allows you to do more with less code, and easy to maintain. Of course, learning a new tool always requires time investment, and you may not see the immediate effect at the beginning. However, if you have a steady work as a Rails developer and continuously build websites in certain complexity, then the short-term investment of learning Ruby on Rails will be very worthwhile in the long run.

What Rails is Not

  • As mentioned above, Rails is a web framework for building web applications, and if static HTML file would be solely needed, Rails is not necessary.
  • Rails is not a Content Management System(CMS). CMS is a pre-written website system which allows you to build a website without writing any code. Most popular and mature CMS on the market are written in PHP, such as Drupal and WordPress. We also have some CMS are written in Ruby, such as Radiant. If you have already met your needs by using CMS to build a website, Rails may not be necessary either.
  • Rails is a web framework that helps you build web applications. It is not a programming language.

What is Ruby?

Rails is a web framework written in Ruby, and It’s not a remarkable idea to dive into Rails without any knowledge of it.

Ruby is an open-source, object-oriented and dynamically interpreted programming language with the syntax in philosophy of simplicity, high productivity, elegance and nature. For the main purpose of making programming enjoyable for developers, Rails is created by Yukihiro Matsumoto (also known as Matz) from Japan, whom is inspired by Lisp, Perl, and Smalltalk.

Let’s take a straightforward example:

str = "May Ruby be with you!"
5.times { puts str }

There are three things indicated from this example:

  • No need to declare types when it comes to dynamical typing
  • Everything is an object, including numbers
  • Anonymous functions in Code Block expression are ubiquitous

We will introduce the basics of Ruby syntax in other chapter to make sure our readers comprehend rapidly and in detail.

Benefits of Dynamic Programming Languages

Why is it advantageous to use dynamic programming languages (Ruby, Python, PHP, Perl, etc.) rather than static programming languages (such as Java, C++) to develop server-side applications?

The main difference between static and dynamic programming languages is that the former requires declaring variables beforehand, while the latter declare them at runtime. In which means, it depends on whether the program needs to be compiled beforehand or not.

As author Fred Brooks stated in his book, The Mythical Man Month: Essays on Software Engineering, “no matter the programming language chosen, a professional developer will write an average 10 lines of code (LoC) per day.” Therefore, a higher-order programming language which allows us to express ideas can accomplish more functionalities than a lower-order programming language. Comparing to static programming languages, using high-level scripting languages can help us more in:

  • Accomplish more task with less code which should greatly improve the productivity
  • Respond faster to the development needs, allowing for agile development

Nevertheless, dynamic programming languages also have their drawbacks:

  • Execution performance is not as good as static programming languages
  • There is no compile time to check type errors

As time goes on, computers are getting much affordable and its performance gradually improved by memory and storage space upgrading. Not to mention the increasing need for web services by the proliferation of mobile devices. In summary, we are surely aware that there’s more demands for application software under the hardware revolution. On the other hand, due to the improvement of the hardware performance, the cost for manpower becomes significant comparing to the runtime performance of a software. Performance of program execution in dynamic programing languages can already achieve practical results (for example, it can handle 50-500 HTTP requests per second and can expand the architecture by increasing the number of servers). We may use statically-typed language to shorten runtime but it takes more than ten times of the time to develop it. Is it really worth it?

Static programming languages are still dominant in aspects of mobile devices with limited hardware resources and embedded systems , which means we need more time to establish the foothold on dynamic programming languages .

The problem of not having a compile time to check type errors is slowly being reduced in importance through agile practices such as unit testing and Test-driven Development (TDD). Most bugs arise from business logic vulnerabilities rather than type errors.

Why Choose Ruby?

Ruby is an object-oriented programming language that places a strong emphasis on usability, readability, and maintainability of code. Matz, the creator of Ruby, designed the language with the goal of making it easy for the average person to understand (he once said that we are all ordinary people, unlike Lisp which is for superhuman beings). This is why you often hear that code from Ruby is naturally concise and beautiful. You can check out Matz’s Why Ruby? slides or his talks at RubyConf 2008, RubyConf 2009, and Mountain West Ruby Conference 2010 to learn more about Ruby’s philosophy. You may love it!

Ruby is also one of the most successful programming languages for domain-specific languages (DSLs), especially internal DSLs. With DSLs, programs can not only have excellent readability, but can also greatly increase productivity. Successful DSL libraries include Rake build tool, RSpec testing tool, Chef server configuration tool, Cucumber acceptance test, and so forth. These libraries are actively shaping our ideas on software development, and we believe that there will be more interesting DSL libraries in the future.


Back to top

Copyright © 2020-2022 Secure Smarter Service, Inc. This site is powered by KodaCamp.