Poetry of Programming

Its about Ruby on Rails – Kiran Soumya

By

So howzz Rails2.0? Its Awesome !

Added the “rake routes” task, which will list all the named routes created by routes.rb.

All resource-based controllers will be plural by default. This allows a single resource to be mapped in multiple contexts and still refer to the same controller. Example:
  # /avatars/45 => AvatarsController#show
  map.resources :avatars

  # /people/5/avatar => AvatarsController#show
  map.resources :people, :has_one => :avatar

Rendering a HTML page in Iphone using Rails 2.0 Multi View

Speaking of the iPhone, we’ve made it easier to declare “fake” types that are only used for internal routing. Like when you want a special HTML interface just for an iPhone. All it takes is something like this:
  # should go in config/initializers/mime_types.rb
  Mime.register_alias “text/html”, :iphone

  class ApplicationController < ActionController::Base
    before_filter :adjust_format_for_iphone

    private
      def adjust_format_for_iphone
        if request.env[“HTTP_USER_AGENT”] && request.env[“HTTP_USER_AGENT”][/(iPhone|iPod)/]
          request.format = :iphone
        end
      end
  end

  class PostsController < ApplicationController
    def index
      respond_to do |format|
        format.html   # renders index.html.erb
        format.iphone # renders index.iphone.erb
      end
    end
  end
You’re encouraged to declare your own mime-type aliases in the config/initializers/mime_types.rb file. This file is included by default in all new applications.

No more overhead of Requesting a bazillion of Javscript/Stylesheet files

In Rails2.0, Using javascript_include_tag(:all, :cache => true) will turn public/javascripts/.js into a single public/javascripts/all.js file in production, while still keeping the files separate in development, so you can work iteratively without clearing the cache.

Speed your application !

In Rails2.0, If you set ActionController::Base.asset_host = “assets%d.example.com”, we’ll automatically distribute your asset calls (like image_tag) to asset1 through asset4. That allows the browser to open many more connections at a time and increases the perceived speed of your application.

Identify your Record url just by object !

Added a number of conventions for turning model classes into resource routes on the fly. Examples:
  # person is a Person object, which by convention will
  # be mapped to person_url for lookup
  redirect_to(person)
  link_to(person.name, person)
  form_for(person)

API authentication over SSL

It’s terribly simple to use. Here’s an example (there are more in ActionController::HttpAuthentication):
  class PostsController < ApplicationController
    USER_NAME, PASSWORD = “dhh”, “secret”

    before_filter :authenticate, :except => [ :index ]

    def index
      render :text => “Everyone can see me!”
    end

    def edit
      render :text => “I’m only accessible if you know the password”
    end

    private
      def authenticate
        authenticate_or_request_with_http_basic do |user_name, password|
          user_name == USER_NAME && password == PASSWORD
        end
      end
  end

Security

A built-in mechanism for dealing with CRSF attacks. By including a special token in all forms and Ajax requests, you can guard from having requests made from outside of your application. All this is turned on by default in new Rails 2.0 applications and you can very easily turn it on in your existing applications using ActionController::Base.protect_from_forgery (see ActionController::RequestForgeryProtection for more).

Also made it easier to deal with XSS attacks while still allowing users to embed HTML in your pages. The old TextHelper#sanitize method has gone from a black list (very hard to keep secure) approach to a white list approach. If you’re already using sanitize, you’ll automatically be granted better protection. You can tweak the tags that are allowed by default with sanitize as well. See TextHelper#sanitize for details.

Finally, added support for HTTP only cookies. They are not yet supported by all browsers, but you can use them where they are.

Exception handling

Lots of common exceptions would do better to be rescued at a shared level rather than per action. This has always been possible by overwriting rescue_action_in_public, but then you had to roll out your own case statement and call super. Bah. So now we have a class level macro called rescue_from, which you can use to declaratively point certain exceptions to a given action. Example:

  class PostsController < ApplicationController
    rescue_from User::NotAuthorized, :with => :deny_access

    protected
      def deny_access
        …
      end
  end

Cookie store sessions

The default session store in Rails 2.0 is now a cookie-based one. That means sessions are no longer stored on the file system or in the database, but kept by the client in a hashed form that can’t be forged. This makes it not only a lot faster than traditional session stores, but also makes it zero maintenance. There’s no cron job needed to clear out the sessions and your server won’t crash because you forgot and suddenly had 500K files in tmp/session.

This setup works great if you follow best practices and keep session usage to a minimum, such as the common case of just storing a user_id and a the flash. If, however, you are planning on storing the nuclear launch codes in the session, the default cookie store is a bad deal. While they can’t be forged (so is_admin = true is fine), their content can be seen. If that’s a problem for your application, you can always just switch back to one of the traditional session stores (but first investigate that requirement as a code smell).

New request profiler

The new request profiler that can follow an entire usage script and report on the aggregate findings. You use it like this:

  $ cat login_session.rb
  get_with_redirect ‘/’
  say “GET / => #{path}”
  post_with_redirect ‘/sessions’, :username => ‘john’, :password => ‘doe’
  say “POST /sessions => #{path}”
  $ ./script/performance/request -n 10 login_session.rb
And you get a thorough breakdown in HTML and text on where time was spent and you’ll have a good idea on where to look for speeding up the application.

AtomFeedHelper

Makes it even simpler to create Atom feeds using an enhanced Builder syntax. Simple example:

  # index.atom.builder:
  atom_feed do |feed|
    feed.title(“My great blog!”)
    feed.updated((@posts.first.created_at))

    for post in @posts
      feed.entry(post) do |entry|
        entry.title(post.title)
        entry.content(post.body, :type => ‘html’)

        entry.author do |author|
          author.name(“DHH”)
        end
      end
    end
  end

Faster Performance

Active Record has seen a gazillion fixes and small tweaks, but it’s somewhat light on big new features. Something new that we have added, though, is a very simple Query Cache, which will recognize similar SQL calls from within the same request and return the cached result. This is especially nice for N+1 situations that might be hard to handle with :include or other mechanisms. Also drastically improved the performance of fixtures, which makes most test suites based on normal fixture use be 50-100% faster.

More efficient Migrations

create_table :people do |t|
  t.column, “account_id”,  :integer
  t.column, “first_name”,  :string, :null => false
  t.column, “last_name”,   :string, :null => false
  t.column, “description”, :text
  t.column, “created_at”,  :datetime
  t.column, “updated_at”,  :datetime
endNow you can write:

create_table :people do |t|
  t.integer :account_id
  t.string  :first_name, :last_name, :null => false
  t.text    :description
  t.timestamps
end

Clean up your environment

Before Rails 2.0, config/environment.rb files every where would be clogged with all sorts of one-off configuration details. Now you can gather those elements in self-contained files and put them under config/initializers and they’ll automatically be loaded. New Rails 2.0 applications ship with two examples in form of inflections.rb (for your own pluralization rules) and mime_types.rb (for your own mime types). This should ensure that you need to keep nothing but the default in config/environment.rb.

Easier plugin order

This can require that you load, say, acts_as_list before your own acts_as_extra_cool_list plugin in order for the latter to extend the former.

Before, this required that you named all your plugins in config.plugins. Major hassle when all you wanted to say was “I only care about acts_as_list being loaded before everything else”. Now you can do exactly that with config.plugins = [ :acts_as_list, :all ].

3 Responses to So howzz Rails2.0? Its Awesome !

  1. reviews says:

    great site great site great site BRAVO!

  2. amenodimeno says:

    That’s good man, keep it going.

  3. queroeropoo says:

    Good information to me.

Leave a Reply to queroeropoo Cancel reply

Your email address will not be published. Required fields are marked *