5 Awesome New Rails 3 Features

5 Awesome New Rails 3 Features

Tutorial Details
  • Topic: Rails 3
  • Difficulty: N/A

After more than a year of development, Ruby on Rails 3 was officially released to the public a few weeks ago. More than just an iterative update, this highly anticipated release was a major refactoring of the popular Ruby framework. Keep reading to learn five of the most awesome new features in Ruby Rails 3.


1. Unobtrusive JavaScript

One of my favorite new Ruby on Rails 3 features is the introduction of Unobtrusive JavaScript (UJS) to all of its JavaScript helper functions. In previous versions of Rails, JavaScript was generated inline with HTML, causing ugly and somewhat brittle code.

As an example, Rails allows you to use its link_to method to generate a delete link for some object.

<%= link_to "Delete this Post", @post, :confirm => "Do you really want to delete this post?", :method => :delete %>

Using this method in your view would generate the following in Rails 2:

<a href="/posts/6" onclick="if (confirm('Do you really want to delete this post?')) { var f = document.createElement('form');       f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;       var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method');       m.setAttribute('value', 'delete'); f.appendChild(m);f.submit(); };return false;">Delete this Post</a>

Rails 3 would generate something much simpler:

<a href='/posts/6"' rel="nofollow" data-method="delete" data-confirm="Do you really want to delete this post?">Delete this Post</a>

Rails 3 replaces all of the inline JavaScript with a couple of HTML5 attributes. All of the JavaScript event handlers to handle the actual confirmation box and deletion are stored in one central JavaScript file that is included with every rails project.

One big advantage to this new method is that the JavaScript helpers are framework agnostic. Instead of being tied to the Prototype library like you were in Rails 2, you can now choose whatever JavaScript framework you like (Rails apps come with Prototype by default, but jQuery is now officially supported.


2. Improved Security

Another awesome new feature of Rails 3 is that XSS protection is now enabled by default. Rails 2 supported XSS protection through the use of the h method.

<%= h @comment.text %>

The h method would escape html and JavaScript to ensure that no malicious client-side code was executed. This method worked great, but there was one problem: you had to actually remember to use the h method everywhere the user entered input was displayed. If you forgot even one place, then you were vulnerable to an XSS attack.

In Rails 3, all input is escaped by default, taking the burden off of the developer of having to remember to escape everywhere that malicious code might be present. For those times that you do want to allow unescaped data to appear in your view, you can use the raw method to tell Rails 3 not to escape the data.

<%= raw @comment.text %>

3. New Query Engine

Rails 3 includes a cool new query engine that makes it easier to get back the data you want and gives you more flexibilitiy in your controller code. These changes show up in various places, but the most common case is fetching data in your controller. In Rails 2, you could use the find method to retrieve the data you were looking for, passing in arguments to specify conditions, grouping, limits, and any other query information. For example:

@posts = Post.find(:all, :conditions => [ "category IN (?)", categories], :limit => 10, :order => "created_on DESC")

finds the first ten posts within some specified categories ordered by the creation time.

In Rails 3, each of the passed in parameters has its own method, which can be chained together to get the same results.

@posts = Post.where([ "category IN (?)", categories]).order("created_on DESC").limit(10)

The query is not actually executed until the data is needed; so these methods can even be used across multiple statements.

@posts = Post.where([ "category IN (?)", categories])
if(condition_a)
 @posts = @posts.where(['approved=?', true])
else
 @posts = @posts.where(['approved=?', false])
end

This is only a simple example, but should provide you with an idea of some of the ways this new syntax can be more useful.


4. Easier Email

The ActionMailer module has been rewritten to make it a lot easier for your application to send email in Rails 3. There are quite a few changes, but here are a couple of my favorites.

1. Default Settings

In Rails, a Mailer is a class that can have many methods, each of which generally configure and send an email. Previously, you had to set all of the parameters for each email separately in each method.

class UserMailer < ActionMailer::Base

 def welcome_email(user)
    from       "system@example.com"

    # other paramters
 end

 def password_reset(user)
    from       "system@example.com"

    # other parameters

 end

end

In Rails 3, you can specify defaults that can be optionally overwritten in each method.

class UserMailer < ActionMailer::Base
  default :from => 'no-reply@example.com',           :return_path => 'system@example.com'

 def welcome_email(user)
    # no need to specify from parameter  end

end

2. Cleaner APIs

Previous versions of Rails required you to send email using special methods that were dynamically created by ActionMailer. For instance, if you wanted to deliver the welcome email in the example above, you would need to call:

UserMailer.deliver_welcome_email(@user)

ln Rails 3, you can just call

    UserMailer.welcome_email(@user).deliver

This makes more sense semantically, and additionally allows you to retrieve and manipulate the Mail object before delivering the email.


5. Dependency Management

One of the strengths of the Ruby on Rails framework is the plethora of gems available for use by developers. Whether it's authentication, handling financial transactions, handling file uploads, or nearly anything else, chances are a gem exists to help with your problem.

Issues can arise, however, if your gems require other gems, or developers are on different environments, among other things. To help solve these types of situations, Rails 3 adds the Bundler gem to help manage your dependencies. Using Bundler in Rails 3 is extremely simple; add a line for each gem you require in your Gemfile, a file included in the root of each of your applications.

gem 'authlogic'

Once you've included all your gems, run:

    bundle install

and Bundler will download and configure all of the gems and their dependencies that you need for the project.

Bundler also allows you to specify certain gems to only be configured in certain environments (development vs production vs testing).

These are only a few of the many changes included in Ruby on Rails 3. Many of the old APIs still work in Rails, even if they've been deprecated, to make it easier to update. So, if you're on the fence about whether or not to upgrade your existing rails app, then go for it!

Thanks for reading!

Tags: Ruby
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://webdev5.com Mufti

    Wow, nice features. Want to learn ruby on rails but do not have enough time

    • http://www.domainsuperstar.com John Gadbois
      Author

      It’s not too bad if you’re already familiar with MVC frameworks in general. I picked it up pretty quickly coming over from CakePHP.

      • http://www.eirscape.ie Paul McClean

        Me too.

        I think Cake was originally an attempt at a PHP clone of rails. When I started learning Ruby (before I looked at Rails), it was a real “where have you been all my life!” moment. Currently fiddling around with the Sinatra framework, really enjoying it.

  • http://alexpearce.me Alex

    Just as a total aside, Devise seems to me to be a nicer authentication system than Authlogic.

    Anyway, Rails 3 is a massive improvement. The team did an incredible job.

    • Oluf Nielsen

      Devise is great :)!
      And specially to rails 3, didn’t like Authlogic that much.

      But you should totally try Devise out! :)!

  • w1sh

    What is Ruby on Rails? Is that like PHP and WordPress? :)

    • Seb

      It’s a framework for Ruby. It’s quite popular, and CakePHP was “inspired” by it.

      There’s even a few Mac vs PC style ads on youtube, probably made by the community :P

  • http://mileonemedia.com Joe Cianflone

    wow, this looks pretty cool. I haven’t touched rails since v1.6 or 7…I got a feeling that it would take some serious relearning to get back into it. But it’s awesome to see this framework getting better and better.

    • http://www.domainsuperstar.com John Gadbois
      Author

      I started on 2.3.8, but 3.0 has a lot of nice new features, definitely worth checking out.

  • http://11heavens.com Caroline Schnapp

    “As an example, Rails allows you to use its link_to method to generate a delete link for some object.”

    Code example is missing after that.

    • Oluf Nielsen

      Well, that is just something like

      ‘Are you sure?’, :method => :edit %>

      / Oluf Nielsen

  • http://greeksolution.gr istoselidas

    Nice article, hope for more advanced articles in rails! Rails is the biggest web framework right now :).

  • CI

    This is all great stuff.

    One exception to the code shown, because i think this is also a great feature, not the less this has been in Rails 2 too.

    Instead of writing this:

    @posts = Post.where([ "category IN (?)", categories]).order(“created_on DESC”).limit(10)

    You can use this, which gets automatically turned into the original query (since categories is an array).

    @posts = Post.where(:category => categories).order(“created_on DESC”).limit(10)

  • http://www.nexuswebsol.com Muhammad Saqib

    Ruby 3 will be great…but i have been fall in love with Django(python web framework)….

    • http://www.domainsuperstar.com John Gadbois
      Author

      I’ve been thinking about learning it, heard a lot about it lately. What do you like about it better than ROR?

  • Oluf Nielsen

    Well, that is just something like

    ‘Are you sure?’, :method => :delete %>

    / Oluf Nielsen

  • http://www.agenciafly.com.br Jônatan Fróes

    Do you know a good book about Ruby and RoR3?

    • http://www.domainsuperstar.com John Gadbois
      Author

      I believe the new edition of Agile Web Development with Rails will be good. It’s co-authored by the creator of Ruby on Rails.

      • http://tinyurl.com/jonatanfroes2 Jônatan Fróes

        I’ll take a look.
        Thanks :)

    • knt

      http://download.files.namba.kg/files/10482221 but it asks for password to download it,if u really wanna get it
      i can give the password for download it

  • http://www.versailles.com John Gadbois
    Author

    The original code snippet was..

    <%= link_to “Delete this Post”, @post, :confirm => “Do you really want to delete this post?”, :method => :delete %>

    • Oluf Nielsen

      I tried to post that to, but couldn’t..

  • http://www.scottradcliff.com Scott Radcliff

    Of all of the new hotness that Rails 3 offers, I would vote for unobtrusive JavaScript, default XSS, and the ability to declare additional options when you generate a project, such as what JavaScript library you would like to use. Some of the new features/syntax took some getting used to, but I’m settled in an loving it now.

  • http://itvillage.site11.com It Village

    great tutorial. continue good work.

  • http://www.metaspring.com/blog/development/the-metaspring-blog-carnival-issue-9-–-ruby-on-rails?utm_source=comment Julie Cameron

    Great overview of the best new features – we’re pretty excited to dig in and start getting dirty! Especially looking forward to playing around with the new query engine and extremely relieved that the h method is dead! :)

  • Sahan

    Do I need to know Ruby before learning Ruby n Rails? or is it like Jquery where we dnt need a javascript knowledge to get started?

  • http://ezror.com sunny

    @Sahan You don’t need Ruby to get started, but it certainly helps. I learned Rails first and then read a standalone Ruby book.

  • http://hyperlexic.com hyperlexic

    why does Ruby look so foreign to me? i’ve been feeling ‘stuck’ in PHP lately and feel like i’m making it do things it’s not designed to do or something. i don’t know what it is, but the way the framework companies have created the PHP mvc model with all the helpers and whatnot is not meeting my requirements as easy as php used to. i think fighting with Zend’s gdata library was what finally pushed me over the edge. how many friggin class files do i have to traverse to find the ‘get a stupid xml feed’ method? which will eventually be something with a superLongMethodNamethatGetsInTheWayWhileBeingDescriptive – and not having time to spend learning multiple new languages, i narrowed it down to python and ruby. so i did a lot of of the tutorials you find with online virtual console command lines, and i ‘got it’ fairly easily. arrays, objects, strings, methods, yadda. i found that ruby felt a lot like JavaScript in the usage examples – which is another language that continues to amaze me with what it can do, but then i realize this is really going to require a new development environment. wamp is where i am, since i have all my windows based audio/multimedia apps on the same box.

    but i’m feeling the messiness of that development environment in project maintainability now. i tried the windows installers of both python and ruby and while python was definitely more familiar and worked better in windows, the ruby ide i picked started hitting me with all these warnings about ‘uninstalled’ dependencies or ‘gems’ or plugins or whatever they are. i have no problem with the command line or going to linux or whatever it takes, but then you really have to start paying attention to testing units, proper code repository usage, and just getting more professional in general. definitely something to strive for, but it’s a lot more than simply learning a new syntax.

  • http://www.seanmccambridge.com Sean

    Thanks for putting this together. Helps Rails n00bs like me understand what’s going on. Seems like frameworks in general are starting to get a lot smarter. Can’t wait to finally dive in to Ruby and RoR.

  • http://chetankalore.wordpress.com Chetan

    Awesome post buddy :) very helpful.

  • http://kiranatama.com agus @ Outsourcing Company

    I skipped the new Dependency Management feature in Rails 3. I think
    the unobstrusive javascript is cool.

    “Rails 3 replaces all of the inline JavaScript with a couple of HTML5
    attributes. All of the JavaScript event handlers to handle the actual
    confirmation box and deletion are stored in one central JavaScript
    file that is included with every rails project.”

    Since Wheels is based on Rails, not a direct port, some of these ideas
    may not apply but could be used for inspiration/improvements.

  • knt

    cool! let’s diving into RoR :)

  • Rojar

    Guys,If you are looking for migrate your rails2.3 app to rails3.2 app. Then I found one fantastic blog http://ror-developerchoice.blogspot.com/2012/12/rails23-app-to-rails32-migration.html.