You are on page 1of 90

Introduction to RoR:

A beautiful framework for today’s web.

Presented By
Code71 Bangladesh Ltd.

Organized by
BASIS
Preview
• Background
• Business Implication
• Introduction
• ROR and MVC
• Convention over configuration in rails
• ActiveRecord - The Rails ORM framework
• ActionView - The ROR view renderer
• ActionController - The core of a web request in ROR
• Data Migration
• Ajax
• Built in test framework
• Logging framework
• REST support
• Gems and plugins - Package manager for ruby
• Demo application - Build a web application in minutes
• Demo of a real life web application built on rails
• Future of rails
• Q&A

Copyright 2010, Code71 Inc. All rights reserved.


Background of RoR
• Created in 2003 by David Heinemeier Hansson

• Extended by the Rails core team, more than 1,400


contributors
• First public release in July 2004.

• David Heinemeier Hansson had won the "Hacker of the


Year" award for this software package in 2005.
• Rails won the 2006 Jolt Award for best Web
development tool.

Copyright 2010, Code71 Inc. All rights reserved.


Background of RoR
Ruby: a language, comparable to Python or Perl born in 1993!

Ruby on Rails: a framework, written in Ruby built in 2003

Extracted from real world application: As Hansson and others worked on the
application, they found out—for the hundredth time—that Web development is
painful, time-consuming, repetitive and detail-oriented. This made it a good
candidate for coding in Ruby. Goal was to build an application - Basecamp.

In the process of writing this high-level, condensed Ruby code, Hansson started
to abstract away the essentials of the interface, and the result became Ruby on
Rails. It was born from real-world needs, from working code and from the
everyday experiences of developers.

Copyright 2010, Code71 Inc. All rights reserved.


Why Ruby on Rails?
• Out of the box architecture for persistence, logging, build
scripts, test, web-tier components.
• Pragmatic philosophy of convention over configuration
• Built on Ruby, fully featured object-oriented language.
• Built in templating engine to generate web pages, emails, xml
and text documents.
• Well thought out object relationship mapping tool,
ActiveRecord.
• Built in AJAX, REST, Web service, configuration for
development, test and production environment.
• Migration for applying or roll back database changes.
• Comprehensive test framework

Copyright 2010, Code71 Inc. All rights reserved.


Why Ruby on Rails? Contd.
class Project < ActiveRecord::Base

belongs_to :portfolio
has_one :project_manager
has_many :milestones
has_many :deliverables, :through => :milestones

validates_presence_of :name, :description


validates_acceptance_of :non_disclosure_agreement
validates_uniqueness_of :short_name

end

Copyright 2010, Code71 Inc. All rights reserved.


Cons of Ruby on Rails

As Ruby is a dynamic language, more automated


testing is required.

Developers will need to become more disciplined and


rigorous in creating unit tests as part of their
development process.

Rails is optimized for building web applications.

Copyright 2010, Code71 Inc. All rights reserved.


Delivering Business Values
Ruby on Rails simplifies the web development process through its
convention over configuration and Don’t repeat yourself it
fundamentally changes the role of the programmer in web
development.

Instead of asking questions like “How do I get function x to call


method y?”, he is able to focus or how to do something, he is freed
to focus more on the general business logic of the application.

This is why Ruby on Rails and the Agile software development


movement go hand in hand.

Copyright 2010, Code71 Inc. All rights reserved.


Delivering Business Values
• Rails provides an integrated application testing framework that will help find errors
before your users find them which saves money in the long run.

• Rails redefined RAD (Rapid Application Development) for the web. Leveraging this
speed of development has shown to save both time and money.

• Rails also simplifies AJAX to allow for enhanced usability and a more satisfying end user
experience.

• Due to Rails mantra of "convention over configuration", those familiar with the Rails
framework can easily anticipate how the application works resulting in a highly
maintainable code base.

• When Rails first emerged, Rails had a reputation for not being scalable, but newer
versions of Rails have overcome that reputation and now power some of the largest
sites on the internet.

• Rails has a wealth of plugins and third party (commercial and open source) solutions
which prevent developers having to spend time and money reinventing the wheel for each
application.

Copyright 2010, Code71 Inc. All rights reserved.


Rails is Agile
• Individuals and interactions over processes and tools
• No complex configuration, no heavy toolsets

• Working software over comprehensive documentation


• Customer collaboration over contract negotiation
• a framework that delivers working software early in the development cycle.This software may be rough around the edges, but it lets the users
start to get a glimpse of what you’ll be delivering.
• In this way, Rails encourages customer collaboration. When customers seejust how quickly a Rails project can respond to change, they start to
trust that the team can deliver what’s required.

• Responding to change over following a plan


• DRY principal- easy maintenance
• Ruby dynamic language more expressive
• Comprehensive tests -regression

Copyright 2010, Code71 Inc. All rights reserved.


Delivering Business Values
Do not compile.
In Ruby, there is no concept of compilation. Everything runs at
runtime. 

Dynamically enhance the behavior of a class - without a


Decorator
Slim down your code base 10-20% by stripping off all type
declarations and interface declarations.

Ajax it in no time.

With Rails, you don’t need an O/R Mapper.

Using Ruby script to build/deploy/release is better than using


NAnt.
No pain no gain.

Copyright 2010, Code71 Inc. All rights reserved.


Great user quotes
“Rails is the most well thought-out web development
framework I’ve ever used. And that’s in a decade of doing
web applications for a living. I’ve built my own
frameworks, helped develop the Servlet API, and have
created more than a few web servers from scratch.
Nobody has done it like this before.”

-James Duncan Davidson, Creator of Tomcat and Ant

“Ruby on Rails is a breakthrough in lowering the barriers


of entry to programming. Powerful web applications that
formerly might have taken weeks or months to develop
can be produced in a matter of days.”

-Tim O'Reilly, Founder of O'Reilly Media


Copyright 2010, Code71 Inc. All rights reserved.
Great user quotes -contd.
“It is impossible not to notice Ruby on Rails. It has had a
huge effect both in and outside the Ruby community... Rails
has become a standard to which even well-established
tools are comparing themselves to.”

-Martin Fowler, Author of Refactoring, PoEAA, XP


Explained

“Rails is the killer app for Ruby.”

Yukihiro Matsumoto, Creator of Ruby

Copyright 2010, Code71 Inc. All rights reserved.


Great user quotes -contd.
“After researching the market, Ruby on Rails stood out as
the best choice. We have been very happy with that
decision. We will continue building on Rails and consider it
a key business advantage.”

-Evan Williams, Creator of Blogger, ODEO, and Twitter

“Ruby on Rails is astounding. Using it is like watching a


kung-fu movie, where a dozen bad-ass frameworks prepare
to beat up the little newcomer only to be handed their asses
in a variety of imaginative ways.”

-Nathan Torkington, O'Reilly Program Chair for OSCON

Copyright 2010, Code71 Inc. All rights reserved.


Great user quotes-contd.

What sets this framework apart from all of the others is the
preference for convention over configuration making
applications easier to develop and understand.”

-Sam Ruby, ASF(Apache Software Foundation) board of


directors

Copyright 2010, Code71 Inc. All rights reserved.


Great sites built on Rails(Contd.)
News Unlimited
Yes, New york times!! http://www.nytimes.com
Great sites built on Rails(Contd.)
Document Sharing
Yes, Scribd!! http://www.scribd.com/
Great sites built on Rails(Contd.)
Create an online store!
Yes, Shopify!! http://www.shopify.com/
Great sites built on Rails(Contd.)
Check fashion.
Yes, MTV Style!! http://www.mtv.com/
Great sites built on Rails(Contd.)
Social coding.
Yes, Github!! http://github.com/
Great sites built on Rails(Contd.)
Box office in Home.
Yes, HBO!! http://www.hbosouthasia.com/
Great sites built on Rails(Contd.)
Presentation sharing.
Yes, Slideshare!! http://www.slideshare.net/
BREAK
MVC

Copyright 2010, Code71 Inc. All rights reserved.


Rails and MVC

Copyright 2010, Code71 Inc. All rights reserved.


Directory structure in rails:
• app
-Controllers
-Helpers
-Models
Views
• config
-environment.rb
routes.rb
• db
-database.yml
 migrations
• components
• doc
• lib
• log
• public
• script
• test
• vendor

Copyright 2010, Code71 Inc. All rights reserved.


Routes

Connects URLs to Code


GET /patients/17
The application would end up running the show action within the patients
controller

Generates URLs from Code


@patient = Patient.find(17)

<%= link_to "Patient Record", patient_path(@patient) %>


Translates that to a link to a URL such as http://example.com/patients/17

Copyright 2010, Code71 Inc. All rights reserved.


Routes

Default route

map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'

Copyright 2010, Code71 Inc. All rights reserved.


Sample Controller, Action & View
Controller and Action(app/controllers/hello_controller.rb):
class HelloController < ApplicationController
def say_hello
@user_name = “John Doe”
end
end

View(app/views/hello/say_hello.rhtml):
<b>Hello <%=@user_name%>!</b> Welcome to demo app.

Copyright 2010, Code71 Inc. All rights reserved.


Sample Request & Response

Browser Request:

http://localhost:3000/hello/say_hello

Browser Response:

Hello John Doe! Welcome to demo app.

Copyright 2010, Code71 Inc. All rights reserved.


What is migration and why?

What ?
Migration allows us to use Ruby to define changes to our database
schema incrementally, making it possible to use a version control
system to keep things synchronized with the actual code

Why ?
• Allows incremental development of database
• Allows easy roll out of a new version of a database
• Allows easy roll back to previous versions
• Allows to change the database anytime

Copyright 2010, Code71 Inc. All rights reserved.


Understanding Migration Script
Generating a migration script
ruby script/generate migration create_companies

Name of the generated migration script


db/migrate/001_create_companies.rb

In this file we will get a class called


“CreateCompanies”
having two methods “self.up” and “self.down”

• self.up - is used when migrating to a new


version
• self.down - is used to roll back  changes made
in self.up
Copyright 2010, Code71 Inc. All rights reserved.
Understanding Migration Script
class CreateCompanies < ActiveRecord::Migration
def self.up
create_table :companies do |table|
table.column :name, :string
end
end

def self.down
drop_table :companies
end
end

• Migrate to specific version


rake db:migrate VERSION=3

• Migration on different environment


rake db:migrate RAILS_ENV=production

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord

O
bject-relational mapping (ORM) layer supplied with Rails

C
onnects business objects and database tables

C
reates a persistent domain model where logic and data
are presented in one place

P
lays the role of model in MVC architecture.

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord contd.
ActiveRecord closely follows the standard ORM model

• Tables map to classes


• Rows to objects
• Columns to object attributes

ActiveRecord minimizes the amount of configuration that


developers perform

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord Contd.
Tables and classes
Convention:
Table is the underscored plural form of the name of the
class.

Example:
Class Table Class Table
Name Name Name Name
Order orders Person people
TaxAgency tax_agencie Datum data
Batch s
batches Quantity quantities
Diagnosis diagnoses LineItem line_items

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord Contd.
Columns and attributes

Active Record objects correspond to rows in a database


table.

The objects have attributes corresponding to the columns


in the table.

ActiveRecord determines columns in tables dynamically


at runtime.

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord Contd.
Columns and attributes
users table: Users
id integer
first_name string
last_name string
user_name string
password string
User class in models/user.rb
class User < ActiveRecord::Base
end

Objects of user class dynamically contains setter and


getter methods for the columns of users table.

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord Contd.
Create a model object

u = User.create(:first_name => “John”, :last_name=>”Doe”,


:user_name=>”scrumpad”, :password => “anything”

This will execute sql:

INSERT INTO users(first_name, last_name, user_name,


password) VALUES(‘John’, ‘Doe’, ’scrumpad’, ’anything’)

u.first_name will produce “John”


u.last_name will produce “Doe”

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord Contd.
Find a model object
By Id:
u = User.find(1)

By Name:
u = User.find_by_first_name(“John”)

Update a model object


u.first_name = “John1”
u.save

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord Contd.
Conditions to find ActiveRecord

Find all records having first name = “John”


users = User.find(:all, :conditions=>”first_name = ‘John’”)

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord associations
Models:

1. Company
2. User
3. Address
4. Role

Class A Class B Foreign Keys Mapping


class User class Address addresses.user_id One user maps
has_one :address belongs_to :user to zero or one
end end address
class Company class User users.company_id One company
has_many :users belongs_to :company maps to zero or
end end more users
class Role class User roles_users.role_id Any number of
has_and_belongs_to has_and_belongs_to_ma roles_users.user_i roles maps to
_many :users ny :roles d any number of
end end users

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord Validations

V
alidations are methods to validate the contents of a
model object

I
f validation fails an object will not be written to the db. It
will be left in memory with its current invalid state.

V
alidations can be performed on save, create or update

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord Validation Helpers

class User < ActiveRecord::Base


validates_presence_of :user_name, :email
validates_uniqueness_of :user_name
end

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord Callbacks
Allows to write code to be invoked at a particular part of AR lifecycle.

Copyright 2010, Code71 Inc. All rights reserved.


ActiveRecord Callbacks Contd.
Directly
class Order < ActiveRecord::Base
#......
def before_save
self.payment_due ||= Time.now + 30.days
end
end

Using a handler
class Order < ActiveRecord::Base
before_validation :normalize_credit_card_number

after_create do |order|
logger.info "Order #{order.id} created“
end

protected
def normalize_credit_card_number
self.cc_number.gsub!(/-\w/, '' )
end
end

Copyright 2010, Code71 Inc. All rights reserved.


Break

Copyright 2010, Code71 Inc. All rights reserved.


ActionController
• A controller object processes a request

• It looks for a public instance method with the same name as


the incoming action

• If it finds one, that method is invoked - if not, but the controller


implements method_missing, that method is called, passing in
the action name as the first parameter and an empty argument
list

• If no method can be called, the controller looks for a template


named after the current controller and action if found, this
template is rendered

• If none of these things happen, an ‘Unknown Action’

Copyright 2010, Code71 Inc. All rights reserved.


ActionController Contd.
Responding to users
Controllers respond to users in four basic ways

• Render a template – a template is a view. Takes info provided


by controller and uses it to generate response

• Return a string to the browser without rendering a view – rarely


used.

• Can return nothing – for example during AJAX calls

• Can return ‘other’ data to client (other then html) like a pdf, or
word document.

Copyright 2010, Code71 Inc. All rights reserved.


ActionController Contd.
Responding to users
• Controllers always respond once – that means every controller
method only has one call to render – throws multiple render
error otherwise.

• Because it must respond once, controller checks to see if a


response has been generated before it finishes handling a
request.

• If it finds no calls to the above methods – it looks for a template


named after the controller and action and renders it

• You can have multiple templates with the same name – but
different extensions. – ie. .rhtml, .rxml, .rjs.

• Searches in the order above for tempates.


Copyright 2010, Code71 Inc. All rights reserved.
ActionController Contd.
Render method

• At the heart of rendering in Rails


• Takes a hash of options that tell it what to render and how.
• For example:

def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
render :action => :show
else
render :template => "fix_user_errors“
end
end

Copyright 2010, Code71 Inc. All rights reserved.


Templates
• A Template is a file that defines the content of a
response.

• 3 formats
– rhtml – html with imbedded ruby
– rxml – a programmatic way of constructing xml content
– Rjs – generates javascript.

Copyright 2010, Code71 Inc. All rights reserved.


Helpers
• A helper is a module that contains methods that assist
a view.

• They are output-centric and exist to output html (or


view code)

• Why use them? Easier to edit your RHTML, easier to


test your helper files.

• By default each controller gets a helper modlue in the


app/helpers directory.

Copyright 2010, Code71 Inc. All rights reserved.


Helpers Contd.
<h3><%= @page_title || “My charity" %></h3>

• This is a simple example, but if you had this code in


each template you begin to let duplication slip in.

• Say you wanted to modify the title of your store to


‘Chrismas Charity’!

• You have to edit every template.

Copyright 2010, Code71 Inc. All rights reserved.


Helper Contd.
m
odule CharityHelper

def page_title

@page_title || "Pragmatic Store"

end
e
nd
--
--
<
h3><%= page_title %></h3>

Copyright 2010, Code71 Inc. All rights reserved.


Form
form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block)

Options:
1 :multipart - If set to true, the enctype is set to "multipart/form-data".
2 :method - Usually either "get" or "post". If "put", "delete" or another verb is used, a
hidden input with name _method is added to simulate the verb over post.
3 A list of parameters to feed to the URL the form will be posted to.

Example:
<% form_tag {:controller=>”product”, :action=>”create” } do %>
<%= text_field_tag(:product_name) %>
<%= submit_tag(“Save") %>
<% end %>

Generated Code:
<form action="/product/create" method="post">
<input id="my_name" name=“product_name" type="text" />
<input name="commit" type="submit" value=“Save" />
</form>

Copyright 2010, Code71 Inc. All rights reserved.


Advanced Form(form_for) Contd.
form_for(record_or_name_or_array, *args, &proc)

Creates a form and a scope around a specific model object that is used as a base for
questioning about values for the fields.

Example:
<% form_for @product do |f| %>
<%= f.text_field :name %>
<%= f.text_field :price, :size => 10 %>
<%= f.text_field :amount, :size =>5 %>
<%= submit_tag "New Product" %>
<% end %>

Generated Code:
<form action="/products“ id="new_product" method="post">
<input id="product_name" name=“product[name]“ type="text" />
<input id="product_price" name=“product[price]" size="10" type="text" />
<input id="product_amount" name=“product[amount]" size="5" type="text" />
<input id="product_submit" name="commit" type="submit" value="Update" />
</form>
Copyright 2010, Code71 Inc. All rights reserved.
Handling errors in form
error_messages and error_messages_for

Example:
Display all of the error messages

<% form_for(@product) do |f| %>


<%= f.error_messages %>
<!-- different form tags -->
<% end %>

Display error message of a specific field

<% form_for(@product) do |f| %>


<%= error_messages_for :name %>
<!-- different form tags -->
<% end %>

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
Links

<%= link_to_remote "Check Time", :url => { :action => 'get_time' },


:update => 'current_time', %>

<div id="current_time">

</div>

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
Callbacks

<%= link_to_remote "Check Time", :url => { :action => 'get_time' },


:update => 'current_time',
:before => "$('current_time').update('Loading...')" %>

<div id="current_time">

</div>

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
Callbacks
<%= link_to_remote "Check Time",
:update => 'current_time',
:url => { :action => 'get_time' },
:before => "$('indicator').show( )",
:success => "$('current_time').visualEffect('highlight')",
:failure => "alert('There was an error. ')",
:complete => "$('indicator').hide( )" %>

<span id="indicator" style="display: none;">Loading...</span>


<div id="current_time"></div>

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
Ajax Forms

<% form_remote_tag :url => { :action => 'reverse' },


:update => "reversed” do %>

<p>Text to reverse:
<%= text_field_tag 'text_to_reverse' %></p>
<p id="reversed"></p>
<p><%= submit_tag 'Reverse!' %></p>

<% end %>

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
Ajax Buttons
<% form_tag :action => 'reverse' do%>

<p>Text to reverse: <%= text_field_tag 'text_to_reverse' %></p>


<p id="reversed"></p>
<p><%= submit_to_remote 'submit', 'Submit via Ajax',
:update => 'reversed', :url => { :action => 'reverse' } %>
</p>
<p> <%= submit_tag "Submit non-Ajax" %></p>

<% end %>

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
Buttons for arbitrary functions

<%= button_to_function "Greet", "alert('Hello world!')" %>

<%= button_to_function "Check Time",


remote_function(:url => { :action => 'get_time' },
:update => "current_time") %>

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
RJS

RJS is Ruby code that generates JavaScript code

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
RJS
def alert_without_rjs
render :text => "alert('Hello without RJS')",
:content_type => "text/javascript"
end

def alert_with_rjs
render :update do |page|
page.alert "Hello from inline RJS"
end
end

<%= link_to_remote "Alert without RJS", :url => { :action => "alert_without_rjs" } %>

<%= link_to_remote "Alert with RJS", :url => { :action => "alert_with_rjs" } %>

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
RJS files

Controller.rb:
def alert_with_rjs

end

Views/controller/alert_with_rjs.rjs

page.alert "Hello from RJS file"

<%= link_to_remote "Alert with RJS", :url => { :action =>


"alert_with_rjs" } %>

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
Element proxies

<div id="my_div" class="green box">DIV</div>

page[:my_div].show

Generates javascript

$('my_div').show();

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
replace and replace_html

replace_html replaces the contents of an


element (accessed as innerHTML)

replace replaces the whole element,


including its start and end tags (accessed
as outerHTML)

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
replace and replace_html

replace_html.rjs
page[:my_div].replace_html "New Text“

replace.rjs:
page[:my_div].replace "New Text"

Copyright 2010, Code71 Inc. All rights reserved.


Ajax
Effects of replace and replace_html

replace_html replace
Original <body> <body>
<div id="my_div"> DIV </div> <div id="my_div"> DIV </div>
</body> </body>
RJS page[:my_div].replace_html page[:my_div].replace
"New Text" "New Text"
Result <body> <body>
<div id="my_div"> New Text
New Text </body>
</div>
</body>

Copyright 2010, Code71 Inc. All rights reserved.


Logger
Log levels:
• Debug
• Info
• Warn
• Error
• Fatal

Ruby's Logger supports masking levels so the types of messages


recorded in the log can be controlled.

By default, Rails will log all levels (debug and higher) in every
environment except production.

In the production environment, it will only log info and higher. This
behavior can be changed in the configuration for each
environment.

Copyright 2010, Code71 Inc. All rights reserved.


Testing
• Has built-in framework for Unit and Functional test

• Use different database for testing which allows testing


without any danger of production data.

• Generate test file while creating models and controllers

• Rails tests can simulate browser requests and thus you


can test response without having to test it through
browser.

Copyright 2010, Code71 Inc. All rights reserved.


Testing
Fixtures
• Human readable data representations of a table. File
name like table_name.yml

• Allow to populate testing database with predefined data


before tests run.

• While running test framework remove all existing data


from database and dump the fixture data into database

• Stored in test/fixtures/

Copyright 2010, Code71 Inc. All rights reserved.


Testing
Unit Test
• Written for Models
• Testing library is placed on test/unit/ and file name like
model_name_test.rb

Functional Test
• Written against controller instance, simulate request
against it, and make assertions about the responses
• Testing library placed on test/functional/ and file name
like controller_name_test.rb

Copyright 2010, Code71 Inc. All rights reserved.


Unit test example

class UserTest < Test::Unit::TestCase


fixtures :companies, :users, :projects

def test_get_user_by_company
users =
User.get_user_by_company(companies(:one).id)
assert_not_nil users
assert_equal 3,users.length
end
end

Copyright 2010, Code71 Inc. All rights reserved.


Assertions used in unit testing
assert(actual, comment)
assert_equal(expected, actual, comment)
assert_match(pattern, string, message)
assert_nil(object, message)/assert_not_nil
assert_raise(Exception, ..., message) { block ... }
assert_difference(expressions, difference = 1, &block)

Copyright 2010, Code71 Inc. All rights reserved.


Functional test example
class UserControllerTest < Test::Unit::TestCase
fixtures :companies, :users, :projects

def setup
@controller = UserController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@request.env['HTTP_HOST'] = "localhost"
end

def test_get_user
get :show, :id => users(:admin).id
assert_response :success
assert_not_nil assigns(:user)
end
end

Copyright 2010, Code71 Inc. All rights reserved.


Functional test assertions
assert_response :success|:redirect|:missing|:error

assert_redirected_to(:controller => ‘blog’, :action =>‘list’)

assert_template ‘store/index’

Copyright 2010, Code71 Inc. All rights reserved.


Gem/Plugin
A gem/plugin is a component that can add to your
application to extend its functionality. You can write your
own and publish and can use existing one.

Command to install a plugin:


$ ruby script/plugin install plugin_url

Command to install a gem:


$ gem install gem_with_opotion

Copyright 2010, Code71 Inc. All rights reserved.


ActiveSupport
Utility classes and standard library extensions

Examples:
• 20.minutes.ago
• Time_ago_in_words
• 1.gigabyte
• Titelize
• Humanize

Copyright 2010, Code71 Inc. All rights reserved.


Future of ROR-Rails 3
Rails 3 = Rails + Merb

Merb was started two years ago by Ezra Zygmuntowicz as a tiny


framework to serve ERb templates from Mongrel. This quickly grew
into much more and carved out a niche as an alternative Rails
stack. Merbists focused on among other things a small speedy
core, being ORM/JavaScript agnostic, and having a rigorous API
for extensions.

R
ails core: Yes, Rails is a full-stack framework and will remain so,
but there’s no reason we shouldn’t also make it possible to run with
less than the full monty. Rails 3 will make it easy to run just a bare
minimum and then allow you to opt in just the stuff you want, if
that’s necessary for your particular situation. Think “rails myapp—
core” (and “rails myapp—flat”).

Copyright 2010, Code71 Inc. All rights reserved.


Future of ROR-Rails 3
Performance optimizations: Merb has a lot of Rails pieces rewritten
to be faster. We’ll be bringing all that good stuff over. We’ll also
bend the architecture in the places where that’s necessary for a big
yield. In short, Rails 3 will get all the performance attention that the
Merb guys are known for.

F
ramework agnosticism: Rails will always have a default answer to
every question within the stack. If you don’t care about testing
frameworks, you’ll get test/unit. If you don’t care about which ORM,
you’ll get Active Record. But some people do care and want
something else. Some people want RSpec for testing, others want
to use Sequel or Data Mapper for ORM, others again prefer Haml
for templating, and some might prefer jQuery for Ajax. All these
people should feel like Rails is welcoming them with open arms.
Yes, we’ll have a default, but we shouldn’t have any form of
discrimination against alternatives.
Copyright 2010, Code71 Inc. All rights reserved.
Future of Rails-Rails 3

Rigorous API: Too many plugins break when Rails is


updated because it’s not clear where they can safely hook
into the internals and when they’re monkeypatching and
should expect things to break. The Merb guys committed to
a public API with tests to ensure that it wouldn’t break.
They’ll bring over that line of thinking and give Rails 3 a
tested and documented API for extensions that won’t break
willy-nilly with upgrades.

Copyright 2010, Code71 Inc. All rights reserved.


Demo

How a small idea turns into an application, in


Ruby on Rails way

Copyright 2010, Code71 Inc. All rights reserved.


Demo – Live rails application

ScrumPad
www.scrumpad.com

Copyright 2010, Code71 Inc. All rights reserved.


Ruby on Rails

F
or further queries or interest in RoR training contact:

t
raining@code71.com
w
ww.code71.com/training.aspx

Copyright 2010, Code71 Inc. All rights reserved.


Ruby on Rails

Q&A

Copyright 2010, Code71 Inc. All rights reserved.


Presenters
Arifur Rahman
Sr. Software Engineer

http://wannabesoftwareengineer.blogspot.com/

Fuad Bin Omar


Sr. Software Engineer

http://www.fuadcse.blogspot.com

Md. Fattahul Alam


http://fattahulalam.blogspot.com/
Sr. Software Engineer

Copyright 2010, Code71 Inc. All rights reserved.


Ruby on Rails

Thank You

Copyright 2010, Code71 Inc. All rights reserved.