# Presentation: 204659

## Ruby on Rails ::The New Gem of Web Development 

*Ross Pallan *
*IT Project Manager*
*Argonne National Laboratory*
*rpallan@anl.gov*

## Ruby on Rails

- Ruby on Rails is a web application framework written in Ruby, a dynamically typed programming language.  The amazing productivity claims of Rails is the current buzz in the web development community.  If your job is to create or manage web applications that capture and manipulate relational database from a web-based user interface, then Ruby on Rails may be the solution you’ve been looking for to make your web development life easier.
-  In this presentation:
- Get an introduction to Ruby on Rails
- Find out what’s behind the hype
- See it in action by building a fully functional application in minutes

## Ruby is a pure object-oriented programming language with a super clean syntax that makes programming elegant and fun. 
In Ruby, everything is an object
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.

- In Ruby, everything is an object
- 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.

***What is Ruby?***

**Notes:**
Object Oriented - An approach to programming which involves the building of abstracted code objects designed to interact with each other. This is an alternative to the simpler but more common 'procedural programming method'. JAVA and C++ are examples of well known languages that often use this method. 

## 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 – DHH Partner, 37Signals
- http://money.cnn.com/magazines/business2/peoplewhomatter/
- The Rails framework was extracted from real-world web applications. That is, Rails comes from real need, not anticipating what might be needed. The result is an easy to use and cohesive framework that's rich in functionality, and at the same time it does its best to stay out of your way.
- All layers in Rails are built to work together so you Don’t Repeat Yourself and can use a single language from top to bottom.
- Everything in Rails (templates to control flow to business logic) is written in Ruby
- Except for configuration files - YAML

**Notes:**
One Language: Ruby. With just one language, you hope it's a good one, and Ruby doesn't disappoint. Ruby is a full object-oriented language with clean syntax and it has a way of making programming truly fun. Using one language means you don't have to juggle between multiple languages and dialects as you're building your application. 

## Rails Strengths – It’s all about Productivity

- Metaprogramming techniques use programs to write programs. Other frameworks use extensive code generation, which gives users a one-time productivity boost but little else, and customization scripts let the user add customization code in only a small number of carefully selected points
- Metaprogramming replaces these two primitive techniques and eliminates their disadvantages.
- Ruby is one of the best languages for metaprogramming, and Rails uses this capability well.
- Scaffolding
- You often create temporary code in the early stages of development to help get an application up quickly and see how major components work together. Rails automatically creates much of the scaffolding you'll need.

**Notes:**
You might be wondering: Web application frameworks are a dime a dozen, so what's different about Rails? Here are a few things that make Ruby on Rails stand above the crowd: 

Rails can thrive without all of the extensive libraries required by other languages. Ruby's flexibility lets you extend your applications in ways that might have been previously unavailable to you. You'll be able to use a Rails feature called scaffolding to put database-backed user interfaces in front of your customers quickly. Then, as you improve your code, the scaffolding melts away. You'll be able to build database-backed model objects with just a couple of lines of code, and Rails will fill in the tedious details. 

## Rails Strengths – Write Code not Configuration

*Convention over configuration  *
- Most Web development frameworks for .NET or Java force you to write pages of configuration code. If you follow suggested naming conventions, Rails doesn't need much configuration. In fact, you can often cut your total configuration code by a factor of five or more over similar Java frameworks just by following common conventions.
*Naming your data model class with the same name as the corresponding database table*
*‘**id’ as the primary key name*
- Rails introduces the Active Record framework, which saves objects to the database.
- Based on a design pattern cataloged by Martin Fowler, the Rails version of Active Record discovers the columns in a database schema and automatically attaches them to your domain objects using metaprogramming.
- This approach to wrapping database tables is simple, elegant, and powerful.

**Notes:**
Convention over Configuration. Rails works hard to take care of all the repetitive and error-prone chores associated with starting to build a web application, and maintaining it over time. Rails uses simple naming conventions and clever use of reflection to make your work easier with near-zero configuration. 

A central component of Rails is the class ActiveRecord, which maps relational tables to Ruby Objects and thereby to the data manipulated by controllers and shown in views.

ActiveRecord
ActiveMailer
ActiveController
ActionPack

## 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*

- Model encapsulates data that the application manipulates, plus domain-specific logic
- View is a rendering of the model into the user interface
- Controller responds to events from the interface and causes actions to be performed on the model.
*MVC pattern allows rapid change and evolution of the user interface and controller separate from the data model*

**Notes:**
In Rails, the Model and Controller are Ruby classes and Views are HTML/XHTML
Full-Stack Web Framework. Rails is an MVC web framework where models, views, and controllers are fully integrated in a seamless fashion. That means you automatically get all the benefits of an MVC design without the hassle of explicitly configuring each component to play well with the others. 

## 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*
- Three environments: development, testing, and production
- Database Support: Oracle, DB2, SQL Server, MySQL, PostgreSQL, SQLite
- Action Mailer
- Action Web Service
- Prototype for AJAX

**Notes:**
This is a core part of agile software development methodology and enables confident evolution of an application.  Rails has support for three different types of testing:

Built-in testing Rails creates simple automated tests you can then extend. Rails also provides supporting code called harnesses and fixtures that make test cases easier to write and run. Ruby can then execute all your automated tests with the rake utility. 

Three environments: development, testing, and production  Rails gives you three default environments: development, testing, and production. Each behaves slightly differently, making your entire software development cycle easier. For example, Rails creates a fresh copy of the Test database for each test run. 

## 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
- Installing Ruby for Windows
- Download the “One-Click Ruby Installer from _[http://rubyinstaller.rubyforge.org](http://rubyinstaller.rubyforge.org/)_
- Installing Ruby for Mac
- It’s already there!
- RubyGems is a package manager that provides a standard format for distributing Ruby programs and libraries
- Installing Rails
- >gem install rails –include-dependencies

**Notes:**
(in a self-contained format called "gems"), 

## Rails Tutorial

- Create the Rails Application
- Execute the script that creates a new Web application project
**>Rails projectname**
- This command executes an already provided Rails script that creates the entire Web application directory structure and necessary configuration files.

## 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.
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
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.

*/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.*
**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
**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.

***Rails Application Directory Structure***

**Notes:**
App - 	This application organizes your application components. It's got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models). 
Components - This directory holds components-tiny self-contained applications that bundle model, view, and controller. 
Config - 	This directory contains the small amount of configuration code that your application will need, including your database configuration (in database.yml), your Rails environment structure (environment.rb), and routing of incoming Web requests (routes.rb). You can also tailor the behavior of the three Rails environments for test, development, and deployment with files found in the environments directory.
 db - 	Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory. 
Doc -	Ruby has a framework, called RubyDoc, that can automatically generate documentation for code you create. You can assist RubyDoc with comments in your code. This directory holds all the RubyDoc-generated Rails and application documentation. 
Lib -	You'll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries). 
Log - 	Error logs go here. Rails creates scripts that help you manage various error logs. You'll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log). 
Public-	Like the public directory for a Web server, this directory has web files that don't change, such as JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public). 
Script 	This directory holds scripts to launch and manage the various tools that you'll use with Rails. For example, there are scripts to generate code (generate) and launch the Web server (server). 
Test - 	The tests you write and those Rails creates for you all go here. You'll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional). 
Tmp -	Rails uses this directory to hold temporary files for intermediate processing. 
Vendor -	Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) go here. 

## Hello Rails!

- Need a controller and a view
**	****>ruby script/generate controller Greeting**
- Edit app/controllers/greeting_controller.rb
- Add an index method to your controller class
**class GreetingController < ApplicationController**
**  ****def index**
**    ****render :text => "<h1>Hello Rails World!</h1>"**
**  ****end**
**end**
- Renders the content that will be returned to the browser as the response body.
- Start the WEBrick server
**>ruby script/server**
**http://localhost:3000**

**Notes:**
Generate Script – creates models, controllers, scaffold.  Metaprogramming

A class in Ruby is defined by the class keyword with a MixedCase or CamelCase’d name

Methods begin with def and are completed by an end keyword
Classes are also completed using an end keyword
Method names, by convention have words separated by underscores
An instance of a class is created with the [class name].new method
Ruby terminates code with a line break instead of a semicolon.

Greeting is a subclass of another class
A subclass is identified by the ‘<‘
Parent class is ApplicationController

So really, what is a symbol?
Simply, a symbol is something that you use to represent names and strings. What this boils down to is a way to efficiently have descriptive names while saving the space one would use to generate a string for each naming instance.

Symbols are useful whenever you’re going to be reusing a word over and over to represent something else.

## Hello Rails!

- Add another method to the controller
**  ****def hello**
**  ****end**
- Add a template app/views/greeting>hello.rhtml
**<html>**
**  ****<head>**
**    ****<title>Hello Rails World!</title>**
**  ****</head>**
**  ****<body>**
**    ****<h1>Hello from the Rails View!</h1>  **
**  ****</body>**
**</html>**

**Notes:**
Previous example - Not very MVC

the term method refers to a piece of code that is exclusively associated either with a class (called class methods, static methods, or factory methods) or with an object (called instance methods). Like a procedure in procedural programming languages, a method usually consists of a sequence of statements to perform an action, a set of input parameters to parameterize those actions, and possibly an output value (called return value) of some kind. The purpose of methods is to provide a mechanism for accessing (for both reading and writing) the private data stored in an object or a class. 

Controllers carry out your application logic
Load model data into variables, save it back and massage and manipulate it.
But controllers are not concerned with how the data is presented and entered by the users

URL /controller/action/parameter

## Hello Rails!

- ERb - Embedded Ruby. Embedding the Ruby programming language into HTML document. An erb file ends with *.rhtml file extension.*
- Similar to ASP, JSP and PHP, requires an interpreter to execute and replace it with designated HTML code and content.
- Making it Dynamic
- 	**<p>Date/Time: <%= Time.now %></p>**
- Making it Better by using an instance variable to the controller
- 	**@time = Time.now.to_s**
- Reference it in .rhtml **<%= @time %>**
- Linking Pages using the helper method link_to()
-     **<p>Time to say <%= link_to "Goodbye!", :action => "goodbye" %>**

**Notes:**
@variable is an instance variable, available only to one particular instance of the class

Good bye to painful web development

## Building a Simple Event Calendar

- Generate the Model (need a database and table)
- Generate the Application
- Configure Database Access
- Create the Scaffolding
- Build the User Interface
- Include a Calendar Helper
- Export to iCal (iCalendar is a standard for calendar data exchange)

## Create the Event Calendar Database

- Create a Database
- Naming Conventions
*Tables should have names that are English plurals.  For example, the people database holds person objects.*
- Use object identifiers named id.
*Foreign keys should be named object_id.  In Active Record, a row named person_id would point to a row in the people database.*
*ID*
*Created_on*
*Updated_on*
- Edit the config/database.yml
- Create a Model
- Create a Controller

## Rails Scaffolding

- Scaffold
- Building blocks of web based database application
- A Rails scaffold is an auto generated framework for manipulating a model
- CRUD Create, Read, Update, Delete
**>ruby script/generate model Event**
**>ruby script/generate controller Event**
*Instantiate scaffolding by inserting*
***scaffold :event**** into the EventController *
*The resulting CRUD controllers and view templates were created on the fly and not visible for inspection*

## Rails Scaffolding

- Generating Scaffolding Code
- Usage: script/generate scaffold ModelName [ControllerName] [action,...]
**>ruby script/generate scaffold Event Admin**
- Generates both the model and the controller, plus it creates scaffold code and view templates for all CRUD operations.
- This allows you to see the scaffold code and modify it to meet your needs.
***Index***
***List***
***Show***
***New***
***Create***
***Edit***
***Update***
***Destroy***

**Notes:**
Look at the Admin controller

## 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

**Notes:**
The controller method to parse the form - update
The object name @events
Submit Tag – The button’s value

Partial views and helpers for reusing view code

Partials
 	<%= render(:partial => form %> # this will render the file _form.rhtml
Views Like includes
<%= render_component (:action => ‘disply_calendar’, :params => {:context=> :checkout } ) %>

Link_to – Creating links

Rails works around the concept of Layouts, Partials and assorted sundries to make up the View in MVC.

Layout is a skeleton

Header/footer templates

Protecting your application from Cross-Site scripting attacks
The helper method h(string) alias for html_escape()

## User Interface with Style 

- Layouts
- 		/standard.rhtml
- Add **layout "layouts/standard"**  to controller
- Partials
- 		/_header.rhtml
- 		/_footer.rhtml
- Stylesheets
- Publis/stylesheets/*.css
*NOTE: The old notation for rendering the view from a layout was to expose the magic @content_for_layout instance variable. The preferred notation now is to use ****yield ***

## Enhance the Model

- Enhancing the Model
- The model is where all the data-related rules are stored
- Including data validation and relational integrity.
- This means you can define a rule once and Rails will automatically apply them wherever the data is accessed.
- Validations - Creating Data Validation Rules in the Model
- 	**validates_presence_of :name**
- 	**validates_uniqueness_of :name**
**	****validates_length_of :name :**maximum =>10
- Add another Model
- Migrations
- Rake migrate

## Create the Relationship

- Assigning a Category to an Event
- Add a field to Event table to hold the category id for each event
- Provide a drop-down list of categories
- Create Relationship
- Edit models\event.rb
***Class Event < ActiveRecord::Base***
***  ******belongs_to :category***
***end***
- Edit models\category.rb
***Class Category < ActiveRecord::Base***
***  ******has_many :events***
***end***
- An Event belongs to a single category and that a category can be attached to many events

**Notes:**
Event is a subclass of another class
A subclass is identified by the ‘<‘
Parent class is ActiveRecord::Base
Event inherits everything ActiveRecord::Base can do

## Rails Relationships

- Model Relations
- Has_one => One to One relationship
- Belongs_to => Many to One relationship (Many)
- Has_many => Many to One relationship (One)
- Has_and_belongs_to_many =>Many to Many relationships

**Notes:**
Define these

## Associate Categories to Events

- Edit Event Action and Template to assign categories
- 		def new
- 		  @event = Event.new
**	****	****  ****@categories = Category.find(:all) **
**	****	**end
- 		def edit
- 		  @event = Event.find(@params[:id])
**	****	****  ****@categories = Category.find(:all)**
**	****	**end
- Edit _form.rhtml
**<%= select "event", "category_id", @categories.collect {|c| [c.name, c.id]} %>**

**Notes:**
Returns a new array containing the results of the block

## Calendar Helper

- This calendar helper allows you to draw a databound calendar with fine-grained CSS formatting without introducing any new requirements for your models, routing schemes, etc.
**Installation:**
- script/plugin install _[http://topfunky.net/svn/plugins/calendar_helper/](http://topfunky.net/svn/plugins/calendar_helper/)_
-  List plugins in the specified repository:
-    		plugin list --source=http://dev.rubyonrails.com/svn/rails/plugins/
- To copy the CSS files, use
***>ruby script/generate calendar_styles***
**Usage:**
**<%= stylesheet_link_tag 'calendar/blue/style' %>**
**<%= calendar(:year => Time.now.year, :month => Time.now.month) %>**

## iCalendar and Rails	

- gem install icalendar
- Add a method to generate the event:
**require 'icalendar'**
**	****class IcalController < ApplicationController**
**def iCalEvent**
**     ****@myevent = Event.find(params[:id])**
**     ****@cal = Icalendar::Calendar.new**
**      ****event = Icalendar::Event.new**
**      ****event.start = @myevent.starts_at.strftime("%Y%m%dT%H%M%S")**
**      ****event.end = @myevent.ends_at.strftime("%Y%m%dT%H%M%S")**
**      ****event.summary = @myevent.name**
**      ****event.description = @myevent.description**
**      ****event.location = @myevent.location**
**      ****@cal.add event**
**      ****@cal.publish**
**      ****headers['Content-Type'] = "text/calendar; charset=UTF-8" **
**    ****render_without_layout :text => @cal.to_ical**
**  ****end**
**end**

**Notes:**
It’s all about rubygems: 

<%= link_to_image '/images/date.png', :controller => 'ical', :action => :iCalEvent, :id => @event %>
<%= link_to(image_tag("/images/ical.jpg", {:alt => 'Add Event to your Calendar', :size => "30x32", :border => 0, :class=>"paddedImage"}), {:controller => 'ical', :action => :iCalEvent, :id => @event}) %>

## RSS and Rails

- Create a new feed controller
-  **def rssfeed**
**    ****conditions = ['MONTH(starts_at) = ?', Time.now.month]**
**    ****@events = Event.find(:all, :conditions => conditions, :order => "starts_at", :limit =>15)**
**    ****@headers["Content-Type"] = "application/rss+xml"**
**  ****end**
- Create a rssfeed.rxml view
- Add a link tag to standard.rhtml
**<%= auto_discovery_link_tag(:rss, {:controller => 'feed', :action => 'rssfeed'}) %>**

## AJAX and Rails

- Add javascript include to standard.rhtml
**<%= javascript_include_tag :defaults %>**
- Add to Event Controller
**auto_complete_for :event, :location**
- Form Helper
**<%= text_field_with_auto_complete :event, :location%>**

## Summary	

- Rail’s two guiding principles:
- Less software (Don’t Repeat Yourself - DRY)
- Convention over Configuration (Write code not configuration files)
- High Productivity and Reduced Development Time
- How long did it take?
- How many lines of code?
**	****  ****>rake stats**
- Don’t forget documentation...
***>rake appdoc***
- Our experience so far.
- Unless you try to do something beyond what you have already mastered, you will never grow. – Ralph Waldo Emerson

**Notes:**
At the end of the day, Rails is all about helping you stay productive.

## Rails Resources

- Books
- Agile Web Development with Rails –Thomas/DHH
- Programming Ruby - Thomas
- Web sites
- Ruby Language
***http://www.ruby-lang.org/en/***
- Ruby on Rails
**	****http://www.rubyonrails.org/**
- Rails API
*Start the Gem Documentation Server*
**Gem_server  ****http://localhost:8808**
- Top Tutorials
**	****http://www.digitalmediaminute.com/article/1816/top-ruby-on-rails-tutorials**
- MVC architectural paradigm
- 	**http://en.wikipedia.org/wiki/Model-view-controller**
**	****http://java.sun.com/blueprints/patterns/MVC-detailed.html**

## 	David Heinemeier Hansson (Ruby on Rails creator) explained, "Once you've tried developing a substantial application in Java or PHP or C# or whatever," he says, "the difference in Rails will be readily apparent. You gotta feel the hurt before you can appreciate the cure."