JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Introduction to Ruby On Rails

October 13, 2010 by Krishna Srinivasan Leave a Comment

Introduction

This article provides an introduction to Ruby on Rails. Ruby is a programming language that is interpreted and Rails is a framework written on top of Ruby for writing Web Applications. The article starts with an introduction to Ruby with respect to the basic syntax usage and provides plenty of samples for illustrating conditional constructs and looping constructs. Also the advanced concepts like Classes /Objects and modules will also explained with examples. The later section of the article explains Rails and it starts with the basics of the Model View Controller Architecture for writing Rails application.

Ruby Introduction

Ruby is an interpreted language that is easy to use and contains various object oriented features. In this section, we will see the basics of Ruby like variable declaration, conditional constructs, looping, classes/object etc. Readers who are new to ruby can be benefitted with the usage of Ruby in this section.

Hello Word

The following code snippet shows how to declare a variable and store some value in it. It later displays the variable’s value in the console.

[code]hello = "Hello World"
puts hello[/code]

Getting input from user

As seen in the last example, the function puts() can be used to output the content to the console and the method gets() is used to obtain the input from the user.

[code]puts("Enter a number");
number = gets();
puts("The number entered is #{number}");[/code]
Also have a look at how the variable’s value is used within strings. The pattern used will be ‘#{variableName}’ when this variable is used within double-quotes.

Declaring Arrays

Ruby supports the declaration of an array through the following syntax. The index of array location starts from zero.

[code]my_array = ["one", "two"];
puts my_array[1];
puts "Element at location 0 is #{my_array[0]}";

puts "Length of the array is is #{my_array.length}"

fruits = Array.new;
fruits[0] = "Apple";
fruits[1] = "Orange";
fruits[2] = "Grapes";

puts "Length of array is #{fruits.length}"[/code]
The length of the array – which tells the number of elements that an array is holding currently can be determined by calling ‘arrayObject.length’. Another way for declaring a dynamic array is to call ‘Array.new’ and the populate the elements with the normal syntax.

Conditional constructs

The following code snippet illustrates the usage of conditional constructs in Ruby. Note the usage of ‘if’, ‘elsif’ and ‘end’ and the usage of AND operations.

[code]pizza_price = 80;
if (pizza_price < 100)
puts "Price is less";
elsif (pizza_price > 100 &amp;&amp; pizza_price <200)
puts "Price is medium";
else
puts "Price is large"
end[/code]
The above code displays the price based on various ranges just to illustrate the usage of conditional constructs.

Looping

The usage of ‘for’ loop is given below. The code declares a array of programming languages and then iterates over the loop using ‘for’ loop.

[code]languages = ["C", "C++", "Java", ".NET"];

for language in languages
puts "Language is #{language}";
end[/code]

Function

Functions are used to define re-usable logic and it can be invoked multiple times. The usage of functions in Ruby is supported through ‘def’ keyword followed by the function name.

[code]def multiply(a, b)
result = multiply_with_return(a, b);
puts("Inside Multiply without return #{result}");
end

def multiply_with_return(a, b)

puts("Multiplying #{a} with #{b}");
result = a * b;
return result;
end

value = multiply_with_return(10, 10);
puts("Result from multiplying with return is #{value}");
multiply(5, 3);[/code]
Functions can support parameters also. In the above code, we have defined functions ‘multiply’ and ‘multiply_with_return’. The first function uses the parameters passed by the caller and displays the result within the function definition. The second function, after calculating the result, returns the result to the caller.

Classes and Objects

In this section, we will see the usage of classes and objects in Ruby. As known, class represents the template for creating objects which contains the combination of related operations and data.

[code]class Arithmetic
def initialize(a, b)
@a = a;
@b = b;
end

def add()
puts("Addition of #{@a} and #{@b} is #{@a + @b}");
end

def sub()
puts("Subtraction of #{@a} and #{@b} is #{@a – @b}");
end

def multiply()
puts("Multiplication of #{@a} and #{@b} is #{@a * @b}");
end

def divide()
puts("Dividing #{@a} with #{@b} results is #{@a / @b}");
end

end

one_two_arithmetic_object = Arithmetic.new(1, 2);
one_two_arithmetic_object.add();
one_two_arithmetic_object.sub();
one_two_arithmetic_object.multiply();
one_two_arithmetic_object.divide();[/code]
In the above code, we declare a class called ‘Arithmetic’ and supports related functions like ‘add’, ‘sub’, ‘multiply’ and ‘divide’ which does the basic mathematical operations. Callers can create objects for this class and can invoke the various available operations supported by this class. There is a special method available in the class declaration called ‘initialize’ which will be invoked automatically when an object is created for this class.
Also note the syntax for creating an object for the class. It is the class name followed by ‘new’. The parameters following the ‘new’ keyword are the initialization parameters. Here we have passed the initialization arguments ‘1’ and ‘2’ and hence the function ‘initialize’ will be called with these arguments.

Modules

Modules in ruby are used to group larger number of operations together. In the below example code, we have created two modules called ‘Number_Operations’ and ‘String_Operations’. Note that these modules are defined in files ‘module_number_operations.rb’ and ‘module_string_operations.rb’.

[code]module Number_Operations

def Number_Operations.display()
puts "Contains the utility operations related to numbers";
end

end

module String_Operations

def String_Operations.display()
puts "Contains the utility operations related to string";
end

end[/code]
The below code represents the usage of the modules, and for importing the modules within the client applications, the syntax ‘require ‘, should be used. Then the operations are used through the syntax ‘ModuleName.operationName’.

[code]require ‘module_string_operations’
require ‘module_number_operations’

puts String_Operations.display();
puts Number_Operations.display();[/code]

Rails Framework

Ruby is an interpreted programming language and Rails is a framework written on Ruby for building web applications. Rails prefer the approach on convention over configuration which means that when you create a web application using Rails framework, the supporting tools will provide a lot of sensible defaults so that developers can go and hook in only their customizations instead of writing everything from scratch. Also one can see the how faster it will be in developing web applications through Rails when compared with other popular Web application frameworks.
Rails framework follows the pattern of MVC which stands for Model-View –Controller architecture which is a popular standard/pattern for building web applications. When a client, typically a browser is making a request, it is the Controller which will be handling the request initially. Based on various request parameters, it will identity the type of request and forwards the request to the appropriate Model objects. There can be multiple Model objects that can be maintained in a Web application and it is the Controller’s responsibility to choose a particular Model object based on various parameters. The Model object represents the action part as well as the data handling part. It may hit the database or can perform any business actions with respect to the context and finally build the data suitable for getting it displayed.
In this section we will create a Rails starter application that will display some static text in the browser upon client’s request. Rails come with plentiful of utilities that make the developmental tasks easier. Have a look at the following command which will create a web application. The name of the application is ‘hello’ and the ‘new’ subcommand indicates that we want to create a new application.

[code]rails new hello –O[/code]
Executing the above command will produce an output similar to the following.

[code]create
create README
create Rakefile
create config.ru
create .gitignore
create Gemfile
create app
create app/controllers/application_controller.
create app/helpers/application_helper.rb
create app/views/layouts/application.html.erb
create app/mailers
create app/models
create config
create config/routes.rb
create config/application.rb
create config/environment.rb
create config/environments
create config/environments/development.rb
create config/environments/production.rb
create config/environments/test.rb
create config/initializers
create config/initializers/backtrace_silencers
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/initializers/secret_token.rb
create config/initializers/session_store.rb
create config/locales
create config/locales/en.yml
create config/boot.rb
create db
create db/seeds.rb
create doc
create doc/README_FOR_APP
create lib
create lib/tasks
create lib/tasks/.gitkeep
create log
create log/server.log
create log/production.log
create log/development.log
create log/test.log
create public
create public/404.html
create public/422.html
create public/500.html
create public/favicon.ico
create public/index.html
create public/robots.txt
create public/images
create public/images/rails.png
create public/stylesheets
create public/stylesheets/.gitkeep
create public/javascripts
create public/javascripts/application.js
create public/javascripts/controls.js
create public/javascripts/dragdrop.js
create public/javascripts/effects.js
create public/javascripts/prototype.js
create public/javascripts/rails.js
create script
create script/rails
create test
create test/performance/browsing_test.rb
create test/test_helper.rb
create test/fixtures
create test/functional
create test/integration
create test/unit
create tmp
create tmp/sessions
create tmp/sockets
create tmp/cache
create tmp/pids
create vendor/plugins
create vendor/plugins/.gitkeep[/code]
As you can see, the execution of the command creates a standard directory layout containing lots of files and folders. Since Ruby applications are MVC based, the folders ‘app/controllers’, ‘app/models’ and ‘app/views’ contain the files related to Controllers, Models and Views respectively. The ‘db’ folder contains information related to database for various environments like development, testing and production. The ‘configuration’ folder represents the application’s configuration information such as request-action mapping and other dependencies. Test cases related files come under the ‘test’ directory. The ‘public’ directory contains the viewable files that can be accessed directly by the client like html, images etc.
To launch the ‘hello’ application, go to the directory ‘hello’ (this new directory was created in the previous step) and type the following. Ruby installation comes with a pre-configured web server called ‘WEBrick’ and the following command starts the web server in the default port number ‘3000’.

[code]rails server
=> Booting WEBrick
=> Rails 3.0.0 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2010-10-09 00:36:29] INFO WEBrick 1.3.1
[2010-10-09 00:36:29] INFO ruby 1.9.2 (2010-08-18) [i386-mingw32]
[2010-10-09 00:36:29] INFO WEBrick::HTTPServer#start: pid=7816 port=3000[/code]
As soon as the server is started, the application can be accessed through the url ‘http://localhost:3000’. This shows the default page which is located in the folder ‘/public/index.html’. This application really doesn’t do anything other than creating the basic template for a web application with a default page. Let us add the basic functionality of creating a controller and a view. The controller takes the responsibility of intercepting the client’s request and it will redirect the control to the view. The view takes the control and the content of the view will be displayed to the browser. The following screen-shot will be displayed when the browser is accessed with the url ‘http://localhost:3000’.

Execute the following command for creating controller and an action. The ‘controller’ subcommand takes the controller name and the action name as arguments. Here the name of the controller is ‘hello’ and the name of the action is ‘hello_action’

[code]rails generate controller hello hello_action
create app/controllers/hello_controller.rb
route get "hello/hello_action"
invoke erb
exist app/views/hello
create app/views/hello/hello_action.html.erb
invoke test_unit
identical test/functional/hello_controller_test.rb
invoke helper
identical app/helpers/hello_helper.rb
invoke test_unit
identical test/unit/helpers/hello_helper_test.rb[/code]
The execution of the command creates the controller file ‘hello_controller.rb’ in the folder ‘/app/controllers’. Here is the listing for generated ‘hello_controller.rb’ file.

[code]class HelloController < ApplicationController
def hello_action
end
end[/code]

In the above code, the ‘HelloController’ class inherits from the base controller Application. A controller can have multiple actions and one such action provided is ‘hello_action’. This makes the application to be accessed through this way ‘/hello/hello_action’. We haven’t provided an implementation for the action and the default implementation is to look for a view file in the directory ‘/app/views//.html.erb’. The generator is sensible enough to create the file ‘hello_action.html.erb’ in the folder ‘/app/views/hello’. The content of this view file is given below,

[code lang=”html”]
<h1>Hello</h1>
<p>This is a starter application to setup things using Rails framework
[/code]

This is a starter application to setup things using Rails framework
Before accessing the application, delete the file ‘index.html’ present in the ‘/public’ directory, the presence of this file overrides the settings. Now accessing the application through the url ‘http://localhost:3000/hello/hello_action’ will display the following view.

 

Creating Multiple Controllers/Actions and Views

Now that we have a basic understanding on rails, we will extend the above concepts in creating an application that has multiple controllers, actions and views. This sample will illustrate this example by providing the option on displaying the home page of contacts and messages. We will start creating the application by executing the following command,

[code]rails new lister –O[/code]
This creates an application called ‘lister’. Change to the directory of ‘lister’. Now we want to create a controller for ‘contacts’ which will control the home page display and the listing for all contacts. Execute the following command for creating the controller called ‘contacts’.

[code]rails generate controller contacts contacts_home contacts_view[/code]
Other than creating a controller called ‘contacts’, the above command will create two more actions called ‘contacts_home’ and ‘contacts_view’. The execution of the above command would result in an output similar to the following.

[code]create app/controllers/contacts_controller.rb
route get "contacts/contacts_view"
route get "contacts/contacts_home"
invoke erb
create app/views/contacts
create app/views/contacts/contacts_home.html.erb
create app/views/contacts/contacts_view.html.erb
invoke test_unit
create test/functional/contacts_controller_test.rb
invoke helper
create app/helpers/contacts_helper.rb
invoke test_unit
create test/unit/helpers/contacts_helper_test.rb[/code]
The definition of the ‘contacts_controller’ is shown below. Note that other than the regular controller definitions, two action definitions are added to the file.

[code]class ContactsController < ApplicationController
def contacts_home
end
def contacts_view
end
end[/code]
The action ‘contacts_home’ is used to display the home page view for contacts. Here is view definition for ‘contacts_home’ found in ‘/app/views/contacts/contacts_view.html/erb’.

[code lang=”html”]
<html>
<head>
<title>Contacts Home</title>
</head>
<body>
<h1>Contacts Home</h1>
<br>
<br>
<h1>This is the home page for Contacts</h1>
<br>
<%= link_to "Go to Contacts View.", :action => "contacts_view" %>
<br>

</body>
</html>
[/code]
Note that the above view page defines the link to the contacts view and the usage of ruby scriptlets in the above between the symbols ‘<#=’ and ‘%>’. A predefined element ‘link_to’ is defined containing the action attribute expressed as ‘action’. The display name given to the action is ‘Go to Contacts View’. The action name is given as ‘contacts_view’, note that this action name should match the action name which is defined in the controller. The inclusion of this scriptlet will introduce a link in the html page and by clicking on the link, the user will be redirected to the ‘contacts_view’ page.
Access to the link ‘http://localhost:3000/contacts/contacts_home’ will display the following page in the browser.

The code listing for ‘contacts_view’ is given below. Note that this view page has some hard-coded contact entries to get them displayed in the browser. Also the view page includes a reference to the contacts home page.

All Contacts

Name Number
12345 David
67890 Jones
13469 Lisa

[code lang=”html”]
<html>
<head>
<title>Contacts View</title>
</head>
<body>
<h2>All Contacts</h2>

<table border = "1">
<tr>
<th>Name</th>
<th>Number</th>
</tr>

<tr>
<td>12345</td>
<td>David</td>
</tr>

<tr>
<td>67890</td>
<td>Jones</td>
</tr>
<tr>
<td>13469</td>
<td>Lisa</td>
</tr>
</table>
<br>
<%= link_to "Go to Contacts home.", :action => "contacts_home" %>
</body>
</html>

[/code]
Access to the link ‘http://localhost:3000/contacts/contacts_view’ will display the following page in the browser.

Execute the following command for creating the controller ‘messages’ with two actions ‘messages_home’ and ‘messages_view’.

[code]rails generate controller messages messages_home messages_view[/code]

The source code listing for messages_controller ,’messages_home’ and ‘messages_view’ is not included here and it will look similar to the one that we had already seen before. The URLs for accessing the home page and the listing for messages are ‘http://localhost:3000/messages /messages_home’ and ‘http://localhost:3000/messages /messages_view’ respectively.

Conclusion

This article provided an introduction to Ruby on Rails explaining the basics in writing Web applications using the Rails framework. Various code samples were discussed to illustrate the basics of Rails framework in writing controllers, actions and views.

Filed Under: Ruby Tagged With: Rails, Ruby

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved