Ruby On Rails I
Peter Komisar                    v.1                Conestoga College

references: The Ruby & Rails Ecosystem - Fall 2009 - © InfoEther, Inc
http://infoether.com/ruby-and-rails-whitepaper
Rails Guides, rubyonrails.org, http://guides.rubyonrails.org/getting_started.html
Understanding the Ruby on Rails MVC Framework, Web Hosting Hero
http://www.webhostinghero.co.uk/ruby-on-rails-mvc-framework.html


We begin our 'zoom' in on Ruby on Rails with a brief
condensation of a white paper called 'Ruby & Rails
Ecosystem',  published in 2009, by InfoEther. InfoEther
is an organization that promotes Ruby on Rails.

This is certainly a pro-Ruby paper so you might want
to have some salt ready as you contemplate some of
the assertions.

Nonetheless the paper does a fine job of bringing many
facts to the table as well as doing an excellent job of
characterizing the emerging role that Ruby and Ruby
on Rails are playing in today's IT landscape.

The following quote might sound a little strong to a Java
programmer but it is nice place to dive into the conversation
of what 'Ruby On Rails' is.

“I always knew one day Smalltalk would replace Java. I
just didn’t know it would be called Ruby.”
         
        "~ Kent Beck, Creator of “Extreme Programming”


Ruby

While Ruby is as old as Java, invented in 1995, by Yukihiro
Matsumoto, aka 'Matz',  Ruby became international in scope
when the first publications appeared in English in late 2000/
early 2001.

PickAxe


The first and most popular book, 'Programming Ruby' by the
Pragmatic Programmers, was widely known as the “Pick Axe”
book because of the cover illustration. 

// that would be our text!


First Conference

In early 2001, the first international Ruby conference was
held in Tampa, Florida, with 30 people in attendance.


Ruby Central


David Black, Chad Fowler, and Dave Thomas and later Rich
Kilmer, formed Ruby Central, Inc. a non-profit organization
dedicated to the mission of promoting and expanding the
Ruby programming language.

Ruby Central hosted international conferences promoting
Ruby as well as sponsoring various regional conferences.
Ruby Central went on to sponsor RubyForge, a site that
stored source code for open source Ruby projects.


RubyForge

RubyForge was founded by InfoEther (the author of the
white paper that is being condensed in this note.


Purported Ruby Advantages

A Disadvantage


Rails  // Ruby in minor leagues until Rails

Ruby as a result was a minor player as far as software
languages goes, that is, until the appearance of Rails
in 2004.  Without doubt a major turning point came for
Ruby with the invention of the Rails framework.

The Rails  framework, as of 2011 is seven  years old.
Ruby on Rails, which shorts to just  'Rails' was presented
at the fourth Ruby Conference in Washington, DC in 2004. 
Rails author is a the highly talented, David  Heinemeier
Hansson, with the nickname DHH. ( Everyone and everything
to do with Ruby seems to have a nickname. )

Rails was a open source spin-off of a commercial product
called 'Basecamp' controlled  by the '37signals' company
in Chicago.
Hansson released the Rails framework to a core group of
international  open source developers, who significantly
expanded the Ruby on Rails framework.


Another Turning Point;  2008

The 2008 Economic slump prompted many governments
and enterprises to abandon proprietary products in favor
of open source alternatives eliminating licensing costs. 


Right Time Right Place

Rails was in the right place at the right time to take advantage
of the software needs associated with the increasing importance
of the Internet to commercial institutions.

Specifically Ruby on Rails provided database centric Web
applications that could be built and deployed quickly while
simultaneously permitting 'on the fly' changes and updates
to be made.


Coincides with the Rise of Agile Methodologies


Rails just so happened to also tie in with the rise and use
of Agile programming methodologies, which were created
to rapidly speed up the creation of complex software
projects. Rails and Agile have had a mutually reinforcing
inertia.

Rails Quick Deployment Finds Favor with Start-ups 

The Rails frameworks provided for rapid construction
and deployment of complex Web applications. The
deployment times were " typically one-third to one-tenth
the time and expense as an effort done with other a
alternatives". 

"Because of this, Rails found popularity quickly with
investor-funded Web 2.0 start-ups since they could
prototype and deploy their Web applications rapidly"
                                         - the InfoEther White Paper


Rails Really Is 'Ruby on Rails'

Lost sometimes in marketing hype was the fact that
Ruby on Rails was only a framework, a collection of
processes written in the Ruby language that achieved
an intended purpose.

For Rails developers to be truly proficient, they should
at least understand how to program in Ruby well enough
to extend Rails where necessary in provide needed
functionality.


Ruby Corporate Support  

// This infor from a 2009 report. Ruby support has
// probably evolved at most of the following corporations


Engine Yard

From the time the InfoEther paper was written to the present,
March 2011, Ruby momentum seems to have grown further.


Engine Yard Website


http://www.engineyard.com/

EngineYard is a Open Source callaboration which on their
front page state 1900 businesses rely on the Rails platform.
The Oracle logo, imprinted on everything that once was
Sun, is absent at this site. It seems they escaped the Oracle
umbrella.


Trends. Heir Apparent to Java

In March 2008, the Gartner Group published a report that
predicted that the worldwide population of Ruby software
developers would grow from less than a million to over four
million by 2013, a 400% increase in five years.

The report writers probably concluded that the worldwide
population of Java developers would substantially shift to
also doing or focusing more on Ruby (and Rails).

// Not really related but interesting!
http://www.gartner.com/it/page.jsp?id=1278413



Java Vulnerable to Cost-Efficient Competitors


The white paper states that Java is vulnerable to being
overtaken because Ruby, PHP, Python, and other languages
because they have proven to be very viable as cost-effective
alternative technologies.

It is also reasoned that Java became dominant at the time
it did was because the Internet and World Wide Web were
immature.

The white paper asserts that "Now that they are more mature,
the contention is that several languages, all Open Source, will
share dominance and be selected and used based on the
strengths" .

The final criticism of Java, which is holds the dominant market
share in the enterprise is "that it takes too long and costs too
much in both development time and opportunity cost."


Gloss the PDF As a Reference

The rest of the PDF shows the many groups who are using
Ruby in different ways. Details for the following can be found. 


Ruby Framework Overview


Rails is a web application development framework written
in the Ruby language. It attempts to make web programming
easier by making assumptions about what all web programmer
will need. This results in much less code needing to be written.


Rails is Opinionated Software


This describes the position that is taken in Rails that there
is  a best way to do things which the framework encourages.

“If you learn the "The Rails Way” you’ll probably discover a
tremendous increase in productivity."              - RailsGuide


The Rails philosophy includes several guiding principles:
"Representational State Transfer (REST) - a style of software
architecture for distributed hypermedia systems such as the
World Wide Web. . . introduced and defined in 2000 by Roy
Fielding in his doctoral dissertation."                - wikipedia  

// Fielding is one of the authors the HTTP spec. versions 1.0 and 1.1.


MVC Architecture


Rail at its core is based on Model View Controller Architecture.


MVC Benefits


Models
  // typically one table corresponds to one model

A model represents the informational data of the application.
It also holds the 'rules; to manipulate that data. In Rails, models
manage interaction with a database.Typically one table will
correspond to one model in the application. Most business
logic will be housed in the model.


Views   // HTML files augmented with Ruby code

Views make up the application user interface. Rails views
are usually HTML files augmented with embedded Ruby
code. The embedded Ruby code inserts data into the view.
Views handle requests made on an application and supply
responses to a web browser.


Controllers // channel / switch between view and model

Controllers “glue” the model to the view. Rails controllers
mediate incoming requests from the web browser and
requests made on the data models passing results back
for presentation to the browser. 


Rails Components

Rails ships as many individual components.

Following is a brief description of each component. Action
Pack is described as a 'gem' so we include a bit of a
definition first.


What is a Gem?

A Gem is a package that has been built according to the Gem specification.
It is a Ruby library package. Gems are built using the RubyGems package management framework for Ruby.Gem packaging makes importing and installing Ruby libraries very simple.



Action Pack

Action Pack is a single gem that contains Action Controller,
Action View  and Action Dispatch. The “VC” part of “MVC”.

The Action Controller framework processes incoming requests
to a Rails application, extracts parameters, and dispatches them
to the intended action.


Action Controller

Action Controller is the top level controller in a Rails application.
Services provided by Action Controller include

Action View

Action View manages the rail application views. It can create
both HTML and XML output by default.

Action View manages


What is AJAX?   // provides an uninterupted HTTP user interface 

Short for Javascript and XML, used on a client to create interactive web applications.  Ajax allows asynchronous server accesses to occur in the background so that the they do not interfere with the current page display.
In spite of it's name, XML is not a compulsory part of AJAX.



Action Dispatch

Action Dispatch handles routing of web requests, dispatching
within the application or to other 'Rack' applications.

What is Rack? 

Rack provides a minimal interface between web servers supporting Ruby and Ruby frameworks. Rack is a inter-application specification.

 Find out more at http://rack.github.com/ or
http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html

Action Mailer // e-mail 

Action Mailer is a framework used to build e-mail services. It
allows receiving  and processing incoming email and sending
both simple text as well as complex multi-part e-mails based
on templates.

Active Model  // general interface for Object Relationship Mapping

"Active Model provides a defined interface between the Action
Pack gem services and Object Relationship Mapping gems
such as Active Record. Active Model allows Rails to utilize
other ORM frameworks in place of Active Record if your
application needs this."            

Active Record   // the default ORM mapping system

"Active Record is the base for the models in a Rails application.

It provides:

among other services."             

Active Resource  // abstracts away web semantics

"Active Resource provides a framework for managing the
connection between business objects and RESTful web
services. It implements a way to map web-based resources
to local objects with CRUD semantics."

// CRUD abbreviates 'Create Read Update Delete'.

Active Support   // general utilities

"Active Support is an extensive collection of utility classes
and standard Ruby library extensions that are used in the
Rails, both by the core code and by your applications."


Railties  // core Ruby Rail code

"Railties is the core Rails code that builds new Rails
applications and glues the various frameworks and
plugins together in any Rails application."

REST

Rest stands for Representational State Transfer. The
Rails  Guide states the key ideas are based on;

 
-  Quoted Sections are  from the Ruby on Rails Guide


Understanding How Rails MVC Works

The browser provides the clients view. It sends it's request
to the web server which forwards to the dispatcher. The
dispatcher loads the controller. The controller may select
to access the database via Active Record via simple CRUD
commands.

The controller then supplies a response, directly via an Action
view, or via a delegation to Action Web Services or by delivery
to Action Mailer. This is the view that  becomes available in
the browser.

Ruby on Rails Architecture
// Vos Virtual Network, from http://vvn.net/wp/2008/09/18/ruby-on-rails-architecture/


Ruby on Rails MVC


Directory Structure Created Via the Command > 'rails new app'


File/Folder Purpose
Gemfile This file allows specification of gem dependencies needed for the rails application.
README This is a brief instruction manual for the application.
Rakefile This file contains batch jobs that can be run from the terminal.
app/ Contains the controllers, models, and views for your application.
config/ Configure your application’s runtime rules, routes, database, and more.
config.ru Rack configuration for Rack based servers used to start the application.
db/ Shows the current database schema, as well as the database migrations.
doc/ Detailed application documentation
lib/ application extended modules
log/ application log files
public/  'seen by world as is' folder, holds static files, images, javascript, CSS stylesheets
script/ holds rails script that starts the app and other scripts to deploy or run the app
test/ Unit tests, fixtures, and other test apparatus
tmp/ Temporary files
vendor/ Place for all third-party code, includes Ruby Gems, Rails source code (if included) and any plugins containing additional prepackaged functionality.


The rake Command

The rake command is a multi-purpose information tool. It
is Ruby equivalent of the 'make' command and deals with
dependencies and automating routine tasks.

Run with the -T command to see the options.

>rake -T
(in C:/Documents and Settings/Peter/blog)
rake about              # List versions of all Rails frameworks and the env...
rake db:create          # Create the database from config/database.yml for ...
rake db:drop            # Drops the database for the current Rails.env (use...
rake db:fixtures:load   # Load fixtures into the current environment's data...
rake db:migrate         # Migrate the database (options: VERSION=x, VERBOSE...
rake db:migrate:status  # Display status of migrations
rake db:rollback        # Rolls the schema back to the previous version (sp...
rake db:schema:dump     # Create a db/schema.rb file that can be portably u...
rake db:schema:load     # Load a schema.rb file into the database
rake db:seed            # Load the seed data from db/seeds.rb
rake db:setup           # Create the database, load the schema, and initial...
rake db:structure:dump  # Dump the database structure to an SQL file
rake db:version         # Retrieves the current schema version number
rake doc:app            # Generate docs for the app -- also availble doc:ra...
rake log:clear          # Truncates all *.log files in log/ to zero bytes
rake middleware         # Prints out your Rack middleware stack
rake notes              # Enumerate all annotations (use notes:optimize, :f...
rake notes:custom       # Enumerate a custom annotation, specify with ANNOT...
rake rails:template     # Applies the template supplied by LOCATION=/path/t...
rake rails:update       # Update both configs and public/javascripts from R...
rake routes             # Print out all defined routes in match order, with...
rake secret             # Generate a cryptographically secure secret key (t...
rake stats              # Report code statistics (KLOCs, etc) from the appl...
rake test               # Runs test:units, test:functionals, test:integrati...
rake test:recent        # Run tests for {:recent=>"test:prepare"} / Test re...
rake test:uncommitted   # Run tests for {:uncommitted=>"test:prepare"} / Te...
rake time:zones:all     # Displays all time zones, also available: time:zon...
rake tmp:clear          # Clear session, cache, and socket files from tmp/ ...
rake tmp:create         # Creates tmp directories for sessions, cache, sock...



Running Rails



Prerequisites

1. You have to have Ruby installed, 1.87 or higher.

2. Gem needs to be working. Good news, it comes
pre-installed in Ruby 1.92 and works 'right out of the
box'.

3. SQLlite3 should be installed, assuming that this
database will be sufficient to start with.

A Hitch:  Problems were encountered and net searches
confirm there is a glitch in running SQLite3 out of the box
with Ruby version 1.9.2 .

Again Good News:  If you download the SQLLite3 DDL
and put it in the Ruby bin directory everything works
and proceeds as usual.

Here we are providing a recap of material in the Rails
Guide, 'Getting Started with Rails' at section 3,
'Creating a New Rails Project'.


Guide Reference

http://guides.rubyonrails.org/getting_started.html

The note provided below summarizes material from the
Rails Guide regarding running Rails. You may prefer to
follow 'first-hand' from the guide itself.


A New Project in Rails


1. Install Rails

Rails is easy to install via the gem command.


Install Rails

> gem install rails


2. Create a new Project, here Called Blog

A simple command creates the new Blog Project.

Create New Project (Called Blog)

> rails new blog

A Couple Rails Command Variations

 A Simple Version Test

 > rails -v

OUTPUT

Rails 3.0.5


See All Flags With Help Flag

 > rails -h

At the bottom of the list of flags there is the
following description:

rails new
 
The 'rails new' command creates a new Rails application with a default directory structure and configuration at the path you specify.

Example:

 > rails new ~/Code/Ruby/weblog


Another Take of the Directory Structure Created by rails new


The Rubicon Project

Directory of C:\Documents and Settings\Peter\rubicon

3/15/2011  12:59 PM    <DIR>          .
3/15/2011  12:59 PM    <DIR>          ..
3/15/2011  12:59 PM                36 .gitignore
3/15/2011  12:59 PM    <DIR>          app
3/15/2011  12:59 PM    <DIR>          config
3/15/2011  12:59 PM               160 config.ru
3/15/2011  12:59 PM    <DIR>          db
3/15/2011  12:59 PM    <DIR>          doc
3/15/2011  12:59 PM               743 Gemfile
3/15/2011  12:59 PM    <DIR>          lib
3/15/2011  12:59 PM    <DIR>          log
3/15/2011  12:59 PM    <DIR>          public
3/15/2011  12:59 PM               270 Rakefile
3/15/2011  12:59 PM             9,126 README
3/15/2011  12:59 PM    <DIR>          script
3/15/2011  12:59 PM    <DIR>          test
3/15/2011  12:59 PM    <DIR>          tmp
3/15/2011  12:59 PM    <DIR>          vendor
              5 File(s)         10,335 bytes


The Bundler

3  Install the default bundle

The 'bundler' handles gem dependencies in Rails applications.
In the case that no additional gems are required beyond those
in the default Gemfile the simple bundle install command supplies
what is necessary when needed.

Installing the Default Bundle   

> bundle install    

Use bundle show to see what was bundled.

Bundle show    

> bundle show   

>bundle show

Gems included by the bundle:

  * abstract (1.0.0)
  * actionmailer (3.0.5)
  * actionpack (3.0.5)
  * activemodel (3.0.5)
  * activerecord (3.0.5)
  * activeresource (3.0.5)
  * activesupport (3.0.5)
  * arel (2.0.9)
  * builder (2.1.2)
  * bundler (1.0.10)
  * erubis (2.6.6)
  * i18n (0.5.0)
  * mail (2.2.15)
  * mime-types (1.16)
  * polyglot (0.3.1)
  * rack (1.2.2)
  * rack-mount (0.6.13)
  * rack-test (0.5.7)
  * rails (3.0.5)
  * railties (3.0.5)
  * rake (0.8.7)
  * sqlite3 (1.3.3)
  * thor (0.14.6)
  * treetop (1.4.9)
  * tzinfo (0.3.25)


Database Configuration

4. Configure a Database

A new Rails application, by default supplies a database
configuration that uses SQLite3.

Here is the database.yml file found under the config directory
from the application directory structure. This is the default
built to use SQLite. 

The Rails tutorial shows only the development database.
The file below shows a test and production database are
also created.

Default SQLite Configuration File // database.yml

# SQLite version 3.x
#   gem install sqlite3

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.

test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000

The tutorial supplies the following configuration files
for using MySQL and Postgres

MySQL database.yml File Sample // From Rails Guide

development:
  adapter: mysql2
  encoding: utf8
  database: blog_development
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock


Postgresql database.yml File Sample // From Rails Guide

development:
  adapter: postgresql
  encoding: unicode
  database: blog_development
  pool: 5
  username: blog
  password:


While the database is configured it has yet to be
created the following rake command does this. 

Command to Create the Database

> rake db:create


Starting the Rails Server

5. Start the server

A basic configuration and setup is now in place and
the server can be started. The server is started with
the following command.

Server start Command

> rails server

Browse to page at localhost on the port specified.


Example

http://localhost:3000

The default page comes up with some further
configuration tips.

Stop the server with Ctrl-C , ( followed by Y to
to terminate the batch job )


Generating a Controller and a View

Minimally a controller and a view need to be created.
That is done in the next command where home is the
controller.

The output is worth pausing to look at here.

Commands to Generate Home Controller and View

> rails generate controller home index

OUTPUT

 > rails generate controller home index
      create  app/controllers/home_controller.rb
       route  get "home/index"
      invoke  erb
      create    app/views/home
      create    app/views/home/index.html.erb
      invoke  test_unit
      create    test/functional/home_controller_test.rb
      invoke  helper
      create    app/helpers/home_helper.rb
      invoke    test_unit
      create      test/unit/helpers/home_helper_test.rb

Under the app/controllers directory a home_controller.rb
file is created with the following content.


What do you know! It is a Ruby class called HomController
an extension of Application Controller. It defines a single
method that returns index.


home_controller.rb
// the HomeController Class

class HomeController < ApplicationController
  def index
  end
end

The view is the index.html.erb file under apps/views/home.

The index name is an 'action' which we see is the name
of the method of the Home controller. At this point the
index method is empty and returns nil.

Static Files in The Public Directory

Rails gives any static files stored in the public directory
preferential treatment, serving it ahead of any dynamic
content that is generated by controllers.

6. Remove the index.html file in the public directory.
( A less permanent approach is to simply rename it. )

> rm public/index.html

or

> cd public
> ren index.html   bindex.html


Routing to the Home Index Page

7. Using the Routing file to redirect to the home#index

Rails now needs to know where the home page is.
The routing file hold this information in a DSL, or
Domain Specific language. The file is under config
and is called routes.rb.

The routes.rb file informs Rails by which paths incoming
requests can be directed to controllers and actions.

The file has many sample routes. Find the line that
starts :root to and uncomment it and make it point
to "home#index".

This is exampled below


A Few Lines from Routes.rb


  # You can have the root of your site routed with "root"
  # just remember to delete public/index.html.
  root :to => "home#index"

This code tells Rails to map the root action to the home
controller’s index action.

Navigating to http://localhost:3000 in a browser, should
show 'Hello, Rails!'.



Assignment


Repeat the procedure outlined above for running Rails
to the point that the Hello Rails homepage shows in the
browser. ( Steps 1 to 7 )

You can either screenshot each of the commands or
copy them from the console and paste them into your
submission.

Include at appropriate points screen shots of the two
browser outputs, the one which is the default index from
the public directory and the output of the Hello Rails
page that the routing file led to.

The document you generate should be a good record
summarizing the steps to this point of creating a Rails
application.