SlideShare una empresa de Scribd logo
1 de 85
Descargar para leer sin conexión
Introduction to RoR
A beautiful framework for today’s web.

             Presented By
         Code71 Bangladesh Ltd.




              Jan 23, 2010
          Seminar held at 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.
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/
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.
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

Object-relational mapping (ORM) layer supplied with
Rails

Connects business objects and database tables

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

Plays 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 Name Table Name                      Class                       Table Name
                                           Name
Order          orders                      Person                      people
TaxAgency      tax_agencies                Datum                       data
Batch          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 to
 has_one :address      belongs_to :user                                              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_many                  roles_users.user_id   roles maps to any
many :users           :roles                                                         number of users
end                   end


                          Copyright 2010, Code71 Inc. All rights reserved.
ActiveRecord Validations

Validations are methods to validate the contents of a
model object

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

Validations 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.
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.
module CharityHelper
     def page_title
            @page_title || "Pragmatic Store"
     end
end
----
<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.
Advanced Form(form_for)
Example:
<% form_for :product, @product, :url=>{:action => "create"} 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" class="new_product" 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",
   :update => 'current_time',
   :url => { :action => 'get_time' } %>

   <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 => "$('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
   :update => "reversed",
   :url => { :action => 'reverse' } 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(:update => "current_time", :url => { :action =>
    'get_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_in_delta(expected_float, actual_float, delta,message)
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.

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

Framework 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



For further queries or interest in RoR training contact:


             training@code71.com
          www.code71.com/training.aspx




                  Copyright 2010, Code71 Inc. All rights reserved.
Ruby on Rails




                         Q&A




          Copyright 2010, Code71 Inc. All rights reserved.
Ruby on Rails




          Thank You




          Copyright 2010, Code71 Inc. All rights reserved.

Más contenido relacionado

La actualidad más candente

Ruby on Rails 2.1 What's New
Ruby on Rails 2.1 What's NewRuby on Rails 2.1 What's New
Ruby on Rails 2.1 What's NewLibin Pan
 
Migrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsMigrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsSteven Evatt
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails PresentationJoost Hietbrink
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Railsousli07
 
RoR (Ruby on Rails)
RoR (Ruby on Rails)RoR (Ruby on Rails)
RoR (Ruby on Rails)scandiweb
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortegaarman o
 
Why we chose mongodb for guardian.co.uk
Why we chose mongodb for guardian.co.ukWhy we chose mongodb for guardian.co.uk
Why we chose mongodb for guardian.co.ukGraham Tackley
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developergicappa
 
Web Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureWeb Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureToru Kawamura
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012alexismidon
 
JCR In Action (ApacheCon US 2009)
JCR In Action (ApacheCon US 2009)JCR In Action (ApacheCon US 2009)
JCR In Action (ApacheCon US 2009)Carsten Ziegeler
 
Bitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRubyBitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRubyBrian Sam-Bodden
 
Ruby on Rails All Hands Meeting
Ruby on Rails All Hands MeetingRuby on Rails All Hands Meeting
Ruby on Rails All Hands MeetingDan Davis
 
JCR - Java Content Repositories
JCR - Java Content RepositoriesJCR - Java Content Repositories
JCR - Java Content RepositoriesCarsten Ziegeler
 
Ruby - a tester's best friend
Ruby - a tester's best friendRuby - a tester's best friend
Ruby - a tester's best friendPeter Lind
 
Plack basics for Perl websites - YAPC::EU 2011
Plack basics for Perl websites - YAPC::EU 2011Plack basics for Perl websites - YAPC::EU 2011
Plack basics for Perl websites - YAPC::EU 2011leo lapworth
 
Middleware as Code with mruby
Middleware as Code with mrubyMiddleware as Code with mruby
Middleware as Code with mrubyHiroshi SHIBATA
 

La actualidad más candente (20)

Ruby on Rails 2.1 What's New
Ruby on Rails 2.1 What's NewRuby on Rails 2.1 What's New
Ruby on Rails 2.1 What's New
 
Migrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsMigrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain Points
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
RoR (Ruby on Rails)
RoR (Ruby on Rails)RoR (Ruby on Rails)
RoR (Ruby on Rails)
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortega
 
How DSL works on Ruby
How DSL works on RubyHow DSL works on Ruby
How DSL works on Ruby
 
Why we chose mongodb for guardian.co.uk
Why we chose mongodb for guardian.co.ukWhy we chose mongodb for guardian.co.uk
Why we chose mongodb for guardian.co.uk
 
Java presentation
Java presentationJava presentation
Java presentation
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developer
 
Web Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the futureWeb Clients for Ruby and What they should be in the future
Web Clients for Ruby and What they should be in the future
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012
 
JCR In Action (ApacheCon US 2009)
JCR In Action (ApacheCon US 2009)JCR In Action (ApacheCon US 2009)
JCR In Action (ApacheCon US 2009)
 
Bitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRubyBitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRuby
 
Ruby on Rails All Hands Meeting
Ruby on Rails All Hands MeetingRuby on Rails All Hands Meeting
Ruby on Rails All Hands Meeting
 
JCR - Java Content Repositories
JCR - Java Content RepositoriesJCR - Java Content Repositories
JCR - Java Content Repositories
 
Ruby - a tester's best friend
Ruby - a tester's best friendRuby - a tester's best friend
Ruby - a tester's best friend
 
How Flipkart scales PHP
How Flipkart scales PHPHow Flipkart scales PHP
How Flipkart scales PHP
 
Plack basics for Perl websites - YAPC::EU 2011
Plack basics for Perl websites - YAPC::EU 2011Plack basics for Perl websites - YAPC::EU 2011
Plack basics for Perl websites - YAPC::EU 2011
 
Middleware as Code with mruby
Middleware as Code with mrubyMiddleware as Code with mruby
Middleware as Code with mruby
 

Similar a Ror Seminar With agilebd.org on 23 Jan09

Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010arif44
 
Ruby Rails Web Development.pdf
Ruby Rails Web Development.pdfRuby Rails Web Development.pdf
Ruby Rails Web Development.pdfAyesha Siddika
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfKaty Slemon
 
Ruby on rails backend development preferred choice for product owners
Ruby on rails backend development preferred choice for product ownersRuby on rails backend development preferred choice for product owners
Ruby on rails backend development preferred choice for product ownersKaty Slemon
 
8 awesome benefits of ruby on rails application development
8 awesome benefits of ruby on rails application development 8 awesome benefits of ruby on rails application development
8 awesome benefits of ruby on rails application development rorbitssoftware
 
Ruby On Rails Presentation
Ruby On Rails PresentationRuby On Rails Presentation
Ruby On Rails PresentationPaul Pajo
 
At&T Interactive: The Many Facets Of Ruby
At&T Interactive: The Many Facets Of RubyAt&T Interactive: The Many Facets Of Ruby
At&T Interactive: The Many Facets Of RubyCoby Randquist
 
Ruby on Rails Web Development Best Practices and Tips.pdf
Ruby on Rails Web Development Best Practices and Tips.pdfRuby on Rails Web Development Best Practices and Tips.pdf
Ruby on Rails Web Development Best Practices and Tips.pdflubnayasminsebl
 
Things you must know on ruby on rails single page application
Things you must know on ruby on rails single page applicationThings you must know on ruby on rails single page application
Things you must know on ruby on rails single page applicationAndolasoft Inc
 
Make your app idea a reality with Ruby On Rails
Make your app idea a reality with Ruby On RailsMake your app idea a reality with Ruby On Rails
Make your app idea a reality with Ruby On RailsNataly Tkachuk
 
Ruby on Rails Development Services
Ruby on Rails Development ServicesRuby on Rails Development Services
Ruby on Rails Development ServicesSpritleSoftware
 
Rho mobile v4 - DroidCon Paris 18 june 2013
Rho mobile v4 - DroidCon Paris 18 june 2013Rho mobile v4 - DroidCon Paris 18 june 2013
Rho mobile v4 - DroidCon Paris 18 june 2013Paris Android User Group
 
Top Essential Features of Ruby on Rails Web Development.pdf
Top Essential Features of Ruby on Rails Web Development.pdfTop Essential Features of Ruby on Rails Web Development.pdf
Top Essential Features of Ruby on Rails Web Development.pdfBoTree Technologies
 
Why is ruby on rails worth investing in 2022
Why is ruby on rails worth investing in 2022 Why is ruby on rails worth investing in 2022
Why is ruby on rails worth investing in 2022 rorbitssoftware
 
Ruby on Rails best resources for self
Ruby on Rails best resources for selfRuby on Rails best resources for self
Ruby on Rails best resources for selfDurga Prasad Tumu
 
Reasons to Pick Ruby on Rails for Web Development Projects!.pdf
Reasons to Pick Ruby on Rails for Web Development Projects!.pdfReasons to Pick Ruby on Rails for Web Development Projects!.pdf
Reasons to Pick Ruby on Rails for Web Development Projects!.pdfShelly Megan
 
Ruby Rails Web Development SEO Expert Bangladesh LTD.pdf
Ruby Rails Web Development  SEO Expert Bangladesh LTD.pdfRuby Rails Web Development  SEO Expert Bangladesh LTD.pdf
Ruby Rails Web Development SEO Expert Bangladesh LTD.pdfTasnim Jahan
 
Ruby on Rails : First Mile
Ruby on Rails : First MileRuby on Rails : First Mile
Ruby on Rails : First MileGourab Mitra
 
8 Common Ruby on Rails Development Mistakes to Avoid
8 Common Ruby on Rails Development Mistakes to Avoid8 Common Ruby on Rails Development Mistakes to Avoid
8 Common Ruby on Rails Development Mistakes to Avoidrorbitssoftware
 

Similar a Ror Seminar With agilebd.org on 23 Jan09 (20)

Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010
 
Ruby Rails Web Development.pdf
Ruby Rails Web Development.pdfRuby Rails Web Development.pdf
Ruby Rails Web Development.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
Ruby on rails backend development preferred choice for product owners
Ruby on rails backend development preferred choice for product ownersRuby on rails backend development preferred choice for product owners
Ruby on rails backend development preferred choice for product owners
 
8 awesome benefits of ruby on rails application development
8 awesome benefits of ruby on rails application development 8 awesome benefits of ruby on rails application development
8 awesome benefits of ruby on rails application development
 
Ruby On Rails Presentation
Ruby On Rails PresentationRuby On Rails Presentation
Ruby On Rails Presentation
 
At&T Interactive: The Many Facets Of Ruby
At&T Interactive: The Many Facets Of RubyAt&T Interactive: The Many Facets Of Ruby
At&T Interactive: The Many Facets Of Ruby
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Ruby on Rails Web Development Best Practices and Tips.pdf
Ruby on Rails Web Development Best Practices and Tips.pdfRuby on Rails Web Development Best Practices and Tips.pdf
Ruby on Rails Web Development Best Practices and Tips.pdf
 
Things you must know on ruby on rails single page application
Things you must know on ruby on rails single page applicationThings you must know on ruby on rails single page application
Things you must know on ruby on rails single page application
 
Make your app idea a reality with Ruby On Rails
Make your app idea a reality with Ruby On RailsMake your app idea a reality with Ruby On Rails
Make your app idea a reality with Ruby On Rails
 
Ruby on Rails Development Services
Ruby on Rails Development ServicesRuby on Rails Development Services
Ruby on Rails Development Services
 
Rho mobile v4 - DroidCon Paris 18 june 2013
Rho mobile v4 - DroidCon Paris 18 june 2013Rho mobile v4 - DroidCon Paris 18 june 2013
Rho mobile v4 - DroidCon Paris 18 june 2013
 
Top Essential Features of Ruby on Rails Web Development.pdf
Top Essential Features of Ruby on Rails Web Development.pdfTop Essential Features of Ruby on Rails Web Development.pdf
Top Essential Features of Ruby on Rails Web Development.pdf
 
Why is ruby on rails worth investing in 2022
Why is ruby on rails worth investing in 2022 Why is ruby on rails worth investing in 2022
Why is ruby on rails worth investing in 2022
 
Ruby on Rails best resources for self
Ruby on Rails best resources for selfRuby on Rails best resources for self
Ruby on Rails best resources for self
 
Reasons to Pick Ruby on Rails for Web Development Projects!.pdf
Reasons to Pick Ruby on Rails for Web Development Projects!.pdfReasons to Pick Ruby on Rails for Web Development Projects!.pdf
Reasons to Pick Ruby on Rails for Web Development Projects!.pdf
 
Ruby Rails Web Development SEO Expert Bangladesh LTD.pdf
Ruby Rails Web Development  SEO Expert Bangladesh LTD.pdfRuby Rails Web Development  SEO Expert Bangladesh LTD.pdf
Ruby Rails Web Development SEO Expert Bangladesh LTD.pdf
 
Ruby on Rails : First Mile
Ruby on Rails : First MileRuby on Rails : First Mile
Ruby on Rails : First Mile
 
8 Common Ruby on Rails Development Mistakes to Avoid
8 Common Ruby on Rails Development Mistakes to Avoid8 Common Ruby on Rails Development Mistakes to Avoid
8 Common Ruby on Rails Development Mistakes to Avoid
 

Último

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Último (20)

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Ror Seminar With agilebd.org on 23 Jan09

  • 1. Introduction to RoR A beautiful framework for today’s web. Presented By Code71 Bangladesh Ltd. Jan 23, 2010 Seminar held at BASIS,
  • 2. 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.
  • 3. 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.
  • 4. 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.
  • 5. 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.
  • 6. 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.
  • 7. 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.
  • 8. 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.
  • 9. 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.
  • 10. 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.
  • 11. 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.
  • 12. 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.
  • 13. 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.
  • 14. 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.
  • 15. Great sites built on Rails(Contd.) News Unlimited Yes, New york times!! http://www.nytimes.com
  • 16. Great sites built on Rails(Contd.) Document Sharing Yes, Scribd!! http://www.scribd.com/
  • 17. Great sites built on Rails(Contd.) Create an online store! Yes, Shopify!! http://www.shopify.com/
  • 18. Great sites built on Rails(Contd.) Check fashion. Yes, MTV Style!! http://www.mtv.com/
  • 19. Great sites built on Rails(Contd.) Social coding. Yes, Github!! http://github.com/
  • 20. Great sites built on Rails(Contd.) Box office in Home. Yes, HBO!! http://www.hbosouthasia.com/
  • 21. Great sites built on Rails(Contd.) Presentation sharing. Yes, Slideshare!! http://www.slideshare.net/
  • 22. MVC Copyright 2010, Code71 Inc. All rights reserved.
  • 23. Rails and MVC Copyright 2010, Code71 Inc. All rights reserved.
  • 24. 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.
  • 25. 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.
  • 26. 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.
  • 27. 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.
  • 28. 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.
  • 29. 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.
  • 30. ActiveRecord Object-relational mapping (ORM) layer supplied with Rails Connects business objects and database tables Creates a persistent domain model where logic and data are presented in one place Plays the role of model in MVC architecture. Copyright 2010, Code71 Inc. All rights reserved.
  • 31. 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.
  • 32. ActiveRecord Contd. Tables and classes Convention: Table is the underscored plural form of the name of the class. Example: Class Name Table Name Class Table Name Name Order orders Person people TaxAgency tax_agencies Datum data Batch batches Quantity quantities Diagnosis diagnoses LineItem line_items Copyright 2010, Code71 Inc. All rights reserved.
  • 33. 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.
  • 34. 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.
  • 35. 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.
  • 36. 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.
  • 37. 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.
  • 38. 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 to has_one :address belongs_to :user 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_many roles_users.user_id roles maps to any many :users :roles number of users end end Copyright 2010, Code71 Inc. All rights reserved.
  • 39. ActiveRecord Validations Validations are methods to validate the contents of a model object If validation fails an object will not be written to the db. It will be left in memory with its current invalid state. Validations can be performed on save, create or update Copyright 2010, Code71 Inc. All rights reserved.
  • 40. 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.
  • 41. ActiveRecord Callbacks Allows to write code to be invoked at a particular part of AR lifecycle. Copyright 2010, Code71 Inc. All rights reserved.
  • 42. 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.
  • 43. 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.
  • 44. 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.
  • 45. 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.
  • 46. 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.
  • 47. 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.
  • 48. 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.
  • 49. 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.
  • 50. Helper Contd. module CharityHelper def page_title @page_title || "Pragmatic Store" end end ---- <h3><%= page_title %></h3> Copyright 2010, Code71 Inc. All rights reserved.
  • 51. 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.
  • 52. 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.
  • 53. Advanced Form(form_for) Example: <% form_for :product, @product, :url=>{:action => "create"} 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" class="new_product" 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.
  • 54. 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.
  • 55. Ajax Links <%= link_to_remote "Check Time", :update => 'current_time', :url => { :action => 'get_time' } %> <div id="current_time"></div> Copyright 2010, Code71 Inc. All rights reserved.
  • 56. Ajax Callbacks <%= link_to_remote "Check Time", :update => 'current_time', :url => { :action => 'get_time' }, :before => "$('current_time').update('Loading...')" %> <div id="current_time"></div> Copyright 2010, Code71 Inc. All rights reserved.
  • 57. 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.
  • 58. Ajax Ajax Forms <% form_remote_tag :update => "reversed", :url => { :action => 'reverse' } 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.
  • 59. 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.
  • 60. Ajax Buttons for arbitrary functions <%= button_to_function "Greet", "alert('Hello world!')" %> <%= button_to_function "Check Time", remote_function(:update => "current_time", :url => { :action => 'get_time' }) %> Copyright 2010, Code71 Inc. All rights reserved.
  • 61. Ajax RJS RJS is Ruby code that generates JavaScript code Copyright 2010, Code71 Inc. All rights reserved.
  • 62. 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.
  • 63. 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.
  • 64. 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.
  • 65. 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.
  • 66. 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.
  • 67. 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.
  • 68. 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.
  • 69. 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.
  • 70. 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.
  • 71. 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.
  • 72. 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.
  • 73. Assertions used in unit testing assert(actual, comment) assert_equal(expected, actual, comment) assert_in_delta(expected_float, actual_float, delta,message) 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.
  • 74. 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.
  • 75. 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.
  • 76. 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.
  • 77. 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.
  • 78. 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. Rails 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.
  • 79. 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. Framework 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.
  • 80. 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.
  • 81. Demo How a small idea turns into an application, in Ruby on Rails way Copyright 2010, Code71 Inc. All rights reserved.
  • 82. Demo – Live rails application ScrumPad www.scrumpad.com Copyright 2010, Code71 Inc. All rights reserved.
  • 83. Ruby on Rails For further queries or interest in RoR training contact: training@code71.com www.code71.com/training.aspx Copyright 2010, Code71 Inc. All rights reserved.
  • 84. Ruby on Rails Q&A Copyright 2010, Code71 Inc. All rights reserved.
  • 85. Ruby on Rails Thank You Copyright 2010, Code71 Inc. All rights reserved.