Seminar On
Ruby on Rails
THE NEW GEM OF WEB DEVELOPMENT
Submitted To : Prepared By :
Mr. Naveen Hemrajani Prakash Jodha
Presentation Agenda
Brief Overview Of Ruby
Rails Introduction
Rails Strength
Rails Scripts
Rails Architecture
Rails Framework In Detail
What is Ruby?
Ruby is a pure object-oriented programming language
with a super clean syntax that makes programming
elegant and fun.
Ruby is an interpreted scripting language, just like Perl,
Python and PHP.
Ruby successfully combines Smalltalk's conceptual
elegance, Python's ease of use and learning and Perl's
pragmatism.
Ruby originated in Japan in 1993 by Yukihiro “matz”
Matsumoto, and has started to become popular worldwide in
the past few years as more English language books and
documentation have become available.
Ruby is a metaprogramming language. Metaprogramming is a
means of writing software programs that write or manipulate
other programs thereby making coding faster and more
reliable.
Ruby is Truly Object-Oriented
All classes derived from Object including Class (like
Java) but there are no primitives (not like Java at all)
Ruby uses single-inheritance
Mixins give you the power of multiple inheritance
without the headaches
Modules allow addition of behaviors to a class
Reflection is built in along with lots of other highly
dynamic metadata features
Things like ‘=‘ and ‘+’ that you might think are
operators are actually methods (like Smalltalk)
Other Features
Centralized package management through RubyGems
Implemented on all major platforms
Dynamic reflection and alteration of objects to facilitate
metaprogramming
Automatic garbage collection
Everything is an expression (even statements)
object-oriented with inheritance, mixins and metaclasses
Dynamic typing and Duck typing
Enough About Ruby !
Lets Move To Rails
“Rails is the most well thought- at web development
framework I’ve ever used”
James Duncan Davidson, Creator of Tomcat and Ant
“Ruby on Rails is a breakthrough in lowering the barriers
of entry to programming”
Tim O'Reilly, Founder of O'Reilly Media
“Rails has become a standard to which even well-
established tools are comparing themselves to.”
Martin Fowler, Chief Scientist, Thoughtworks
What is Rails?
Ruby on Rails or just Rails (RoR)
Rails
is an open source Ruby framework for
developing database-backed web applications.
Created by David Heinemeier Hansson .
Everything in Rails (templates to control flow to
business logic) is written in Ruby
Except for configuration files - YAML
Rails Strengths
Convention over configuration
DRY(Don’t Repeat Yourself)
Agile Development
Rails Strengths – Full-Stack Web
Framework
Rails implements the model-view-controller (MVC) architecture. The
MVC design pattern separates the component parts of an application
Rails Strengths
Rails embraces test-driven development.
Unit testing: testing individual pieces of code
Functional testing: testing how individual pieces of code
interact
Integration testing: testing the whole system
Threeenvironments: development, testing, and
production
Database
Support: Oracle, DB2, SQL Server,
MySQL, PostgreSQL, SQLite
Rails Strengths
Rails Libraries
Action Pack
– Action Controller
– Action View
Active Record
Action Webservices
Action Mailer
Active Support
Rails Environment and Installing the
Software
Rails will run on many different Web servers. Most of
your development will be done using WEBrick, but you'll
probably want to run production code on one of the
alternative servers.
Apache, Lighttpd (Lighty),Mongrel
Development Environment
Windows, Linux and OS X
No IDE needed although there a few available like
Eclipse, RadRails
RubyGems is a package manager that provides a standard
format for distributing Ruby programs and libraries
Rails Scripts
Rails also provides some excellent tools that
assist us in the process of developing our
application.
tools are packaged as scripts that we run from
the command-line of whatever operating system
we develop on
Rails Scripts
The most important scripts to become familiar
with and use regularly in our development
are:
RailsConsole
WEBrick Web server
Generators
Migrations
Rails Architecture
Rails applications are implemented using the
Model-View-Controller (MVC)
Model - ActiveRecord
View - ActionView
Controller - ActionController
Rails Architecture
Rails Application Directory Structure
App> contains the core of the application
/models> Contains the models, which encapsulate
application business logic
/views/layouts> Contains master templates for each
controller
/views/controllername> Contains templates for
controller actions
/helpers> Contains helpers, which you can write to
provide more functionality to templates.
Cont..
Config> contains application configuration, plus
per-environment configurability - contains the
database.yml file which provides details of the
database to be used with the application
Db> contains a snapshot of the database schema
and migrations
Log> application specific logs, contains a log for
each environment
Cont..
Public> contains all static files, such as images,
javascripts, and style sheets
Script> contains Rails utility commands
Test> contains test fixtures and code
Vendor> contains add-in modules.
Workflow for creating Rails
applications:
Use the rails command to create the basic skeleton of the
application.
Create a database with necessary definition in the MySQL
server to hold your data.
Configure the application to know where your database is
located and specify the login credentials for it.
Create Rails Active Records ( Models ) because they are the
business objects you'll be working with in your controllers.
Generate Migrations that makes creating and maintaining
database tables and columns easy.
Write Controller Code to put a life in your application.
Create Views to present your data through User Interface.
Creating an Empty Rails Application
Rails is both a runtime web application framework and a set of helper
scripts that automate many of the things you do when developing a
web application. In this step, we will use one such helper script to
create the entire directory structure and the initial set of files to start
our Library System Application.
Go into ruby installation directory to create your application.
Run the following command to create a skeleton for our library
application.
C:\ruby> rails -d mysql library
This will create a subdirectory for the library application containing a
complete directory tree of folders and files for an empty Rails
application. Check a complete directory structure of the application.
Here we are using -d mysql option to specify our interest to use
MySQL database.
By default Rails uses SQLite database.
Starting Web Server:
Rails web application can run under virtually any web server,
but the most convenient way to develop and test a Rails web
application is to use the built-in WEBrick web server.
This server will be started from the application directory as
follows. This runs on port number 3000.
C:\ruby\library\> ruby script/server
This will start your WEBrick web server listening for Web
Requests at port number 3000 at local machine.
Now open your browser and browse to http://127.0.0.1:3000
Database Setup
Ruby on Rails recommends to create three
databases. A database for each development,
testing and production environment. According
to convention their names should be:
library_development
library_production
library_test
You should initialize all three of them and
create a user and password for them with full
read and write privileges.
When you finish, database.yml should look something like as
follows with MySQL console:
development:
adapter: mysql
encoding: utf8
database: library_development
username: root
password: password
host: localhost
Active Records - Models
Rails Active Record is the Object/Relational Mapping (ORM) layer
supplied with Rails. It closely follows the standard ORM model,
which is as follows:
tables map to classes
rows map to objects of those classes
columns map to object attributes
Rails Active Records provides an interface and binding between the
tables in a relational database and the Ruby program code that
manipulates database records. Ruby method names are automatically
generated from the field names of database tables.
Each Active Record object has CRUD (Create, Read, Update, and
Delete) methods for database access. This strategy allows simple
designs and straightforward mappings between database tables and
application objects.
Creating Active Record files
To create the Active Record files for our entities for library
application, issue the following command from the top level of the
application directory.
C:\ruby\library\> ruby script/generate model Book
C:\ruby\library\> ruby script/generate model Subject
You're telling the generator to create models called Book, and
Subject to store instances of books and subjects.
Content available in book.rb
class Book < ActiveRecord::Base
end
Content available in subject.rb
class Subject < ActiveRecord::Base
end
Creating Associations Between Models:
When you have more than one model in your rails application, you
would need to create connection between those models. You can do
this via associations. Active Record supports three types of
associations:
one-to-one : A one-to-one relationship exists when one item has
exactly one of another item. For example, a person has exactly one
birthday or a dog has exactly one owner.
one-to-many : A one-to-many relationship exists when a single
object can be a member of many other objects. For instance, one
subject can have many books.
many-to-many : A many-to-many relationship exists when the first
object is related to one or more of a second object, and the second
object is related to one or many of the first object.
You indicate these associations by adding declarations to your
models: has_one, has_many, belongs_to, and
has_and_belongs_to_many.
Creating Associations Between Models:
To do so, modify book.rb and subject.rb to look like this:
class Book < ActiveRecord::Base
belongs_to :subject
end
class Subject < ActiveRecord::Base
has_many :books
end
Migrations
Rails Migration allows you to use Ruby to define changes to your
database schema, making it possible to use a version control system
to keep things synchronized with the actual code.
This has many uses, including:
Teams of developers - if one person makes a schema change, the
other developers just need to update, and run "rake migrate".
Production servers - run "rake migrate" when you roll out a new
release to bring the database up to date as well.
Multiple machines - if you develop on both a desktop and a
laptop, or in more than one location, migrations can help you keep
them all synchronized.
What can Rails Migration do?
create_table(name, options)
drop_table(name)
rename_table(old_name, new_name)
add_column(table_name, column_name, type, options)
rename_column(table_name, column_name, new_column_name)
change_column(table_name, column_name, type, options)
remove_column(table_name, column_name)
add_index(table_name, column_name, index_type)
remove_index(table_name, column_name)
Migrations support all the basic data types:
string, text, integer, float, datetime, timestamp, time, date, binary and boolean:
ActionController API
The ActionController component provides us within easy-to-use
functionality related to the following areas:
Routing
Interfacing with the Web server
Using sessions
Cache management
Rendering view templates
ActionController
The process for creating a controller is very easy, and it's similar to
the process we've already used for creating a model. We will create
just one controller here:
C:\ruby\library\> ruby script/generate controller Book
It creates a file called app/controllers/book_controller.rb
Built-in Caching
Enhance performance by keeping the result of
calculations, renderings, and database calls around for
subsequent requests
Action Controller offers 3 levels of granularity
Page
Action
Fragment
Sweepers are responsible for expiring caches when
model objects change
Views - ActionView
A Rails View is an ERb program that shares data with
controllers through mutually accessible variable.
If you look in the app/views directory of the library
application, you will see one subdirectory for each of the
controllers we have created (book). Each of these
subdirectories was created automatically when the same-
named controller was created with the generate script.
The View component is all about presenting the data to
the user . The main terms used in the context of View are
◦ Template
◦ Layout
◦ Pagination
Scaffolding
While you're developing Rails applications, especially those which
are mainly providing you with a simple interface to data in a
database, it can often be useful to use the scaffold method.
Scaffolding provides more than cheap demo thrills. Here are some
benefits:
You can quickly get code in front of your users for feedback.
You are motivated by faster success.
You can learn how Rails works by looking at generated code.
You can use the scaffolding as a foundation to jumpstarts your
development.
Create the User Interface
While functional, these templates are barely usable and only
intended to provide you with a starting point
• RHTML files use embedded Ruby mixed with HTML ERb
• <% …%> # executes the Ruby code
• <%= … %> # executes the Ruby code and displays the result
• Helpers
• Layouts
• Partials
• Error Messages
• CSS
• AJAX
Form Helpers
• Start, submit, and end forms
User Interface with Style
Layouts
/standard.rhtml
Add layout "layouts/standard" to controller
Partials
/_header.rhtml
/_footer.rhtml
Stylesheets
Publis/stylesheets/*.css
Rails Success Story
Basecamp (info as of late April ’05)
Average lines of code for an action in Basecamp is 5
Written in 9 months
Tens of thousands of users
300k dynamic page renders/day
Hosted on two app servers with 15 fastcgi processes
each + one MySQL server
THANK YOU