Rails 3.0: It's ready!

Rails 3.0 has been underway for a good two years, so it’s with immense pleasure that we can declare it’s finally here. We’ve brought the work of more than 1,600 contributors together to make everything better, faster, cleaner, and more beautiful.

This third generation of Rails has seen thousands of commits, so picking what to highlight was always going to be tough and incomplete. But here’s a choice selection of major changes for Rails 3:

New Active Record query engine
Active Record has adopted the ARel query engine to make scopes and queries more consistent and composable. This makes it much easier to build complex queries over several iterations. We also delay the actual execution of the query until it’s needed. Here’s a simple example:

<pre style="font-size: 12px">users = User.where(:name => "david").limit(20) users = users.where("age > 29")

  1. SELECT * FROM users
  2. WHERE name = “david” AND age > 29
  3. ORDER BY name
  4. LIMIT 20
    users.order(:name).each { |user| puts user.name }

Read more in new Active Record guide and watch the Dive into Rails 3: ARel video.

New router for Action Controller
When we switched to a REST-based approach for controllers in Rails 2, we patched on the syntax to the existing router while we were waiting to see if the experiment panned out.

It did and for Rails 3 we’ve gone back and revamped the syntax completely to favor the REST style with less noise and more flexibility:

<pre style="font-size: 12px">resources :people do resource :avatar

collection do get :winners, :losers end

end

  1. /sd34fgh/rooms
    scope ‘:token’, :token => /\w{5,5}/ do
    resources :rooms
    end
  1. /descriptions
  2. /pl/descriptions
  3. /en/descriptions
    scope ‘(:locale)’, :locale => /en|pl/ do
    resources :descriptions
    root :to => ‘projects#index’
    end

Read more in the new routing guide.

New Action Mailer
Action Mailer was born with a split-personality of half model, half controller. In Rails 3, we’ve made the choice to make it all controller. This means that the feel and functionality will be much closer to Action Controller and in fact they now share a bunch of underlying code. Here’s a taste of what it looks like now:

<pre style="font-size: 12px">class Notifier < ActionMailer::Base default :from => "Highrise <system@#{APPLICATION_DOMAIN}>"

def new_project(digest, project, person) @digest, @project, @person = digest, project, person attachments[‘digest.pdf’] = digest.to_pdf attachments[‘logo.jpg’] = File.read(project.logo_path) mail( :subject => “Your digest for #{project.name}”, :to => person.email_address_with_name ) do |format| format.text { render :text => “Something texty” } format.html { render :text => “Something texty” } end end

end

The new Action Mailer is built on top of the new Mail gem as well. Say goodbye to TMail headaches.

Read more in new Action Mailer guide.

Manage dependencies with Bundler
Managing all the dependencies of a Rails application has long been a hassle of patchworks. We had config.gem, Capistrano externals, custom rake setup tasks, and other incomplete solutions.

Bundler cleans all that up and allows you to specify the libraries, frameworks, and plugins that your application depends on. All Rails 3 applications are born with a Gemfile to control it all. See more on the Bundler site.

XSS protection by default
The internet is a scary place and Rails 3 is watching out for you by default. We’ve had CRSF protection with form signing for a while and SQL-injection protection since the beginning, but Rails 3 ups the anté with XSS protection as well (hat tip to Django for convincing us).

See the Railscast on XSS video and the Dive into Rails 3: Cross-site scripting video for more.

Say goodbye to encoding issues
If you browse the Internet with any frequency, you will likely encounter the &#xFFFD; character. This problem is extremely pervasive, and is caused by mixing and matching content with different encodings.

In a system like Rails, content comes from the database, your templates, your source files, and from the user. Ruby 1.9 gives us the raw tools to eliminate these problems, and in combination with Rails 3, &#xFFFD; should be a thing of the past in Rails applications. Never struggle with corrupted data pasted by a user from Microsoft Word again!

Active Model: Validations, callbacks, etc for all models
We’ve extracted quite a bit of commonly requested Active Record components into the new Active Model framework. This allows an ORM like Mongoid to use Active Record’s validations, callbacks, serialization, and i18n support.

Additionally, in the rewrite of Action Controller, we removed any direct references to Active Record, defining a clean, simple API that ORMs can implement. If you use an API-compliant ORM (like DataMapper, Sequel, or Mongoid), you will be able to use features like form_for, link_to and redirect_to with objects from those ORMs without any additional work.

Official plugin APIs
We also rewrote Railties with the express goal of using the new plugin API for all Rails frameworks like Active Record and Action Mailer. This means that Rails plugins like the ones for DataMapper and RSpec have access to all of the integration as the built-in support for Active Record and Test::Unit.

The new Railtie API makes it possible to modify the built-in generators, add rake tasks, configure default Rails options, and specify code to run as early, or as late as you need. Rails plugins like Devise were able to add much better integration in the Rails 3 version of their plugin. Expect to see a lot more of that in the months ahead.

Rewritten internals
We rewrote the internals of Action Pack and Railties, making them much more flexible and easier to extend. Instead of a single monolithic ActionController::Base, Rails 3 exposes a number of modules, each with defined APIs, that you can mix and match to create special-purpose controllers for your own use. Both Action Mailer in Rails and the Cells project make heavy use of this new functionality.

You can also take a look a this blog post by Yehuda (from last year) to see how the new architecture makes it easy to implement Django-style generic actions in Rails by leveraging Rack and ActionController::Metal.

The Rails generator system is got a revamp as well. Instead of monolithic generators that know about all of the Rails frameworks, each generator calls a series of hooks, such as :test_framework and :orm, that plugins can register handlers for. This means that generating a scaffold when using rSpec, DataMapper and Haml will generate a scaffold customized for those plugins.

Agnosticism with jQuery, rSpec, and Data Mapper
The rewritten internals and the new plugin APIs have brought true agnosticism to Rails 3 for all components of the framework. Prefer DataMapper to Active Record? No problem. Want to use jQuery instead of Prototype? Go ahead. Eager to test with rSpec instead of test/unit? You got it.

It’s never been easier to Have It Your Way™ with Rails 3. And at the same time, we’ve made that happen without making using the excellent default stack any more complicated.

Documentation
Rails 3 has had a long development cycle and while that might have lead to some impatience, it has also given book and tutorial authors a chance to catch up and be ready. There’s a wealth of great Rails 3 documentation available already and more is coming shortly.

The Agile Web Development with Rails 4th Ed book is almost ready and there are plenty more books coming. Check out all the new guides, the new official videos, new Railscasts, and a new tutorial. See the recent recap of documentation sources for more.

Installation
gem install rails --version 3.0.0.

We also have a Rails v3.0.0 tag and a 3-0-stable branch.

Rails 3.0 has been designed to work with Ruby 1.8.7, Ruby 1.9.2, and JRuby 1.5.2+.

Gratitude and next steps
I’m personally incredibly proud of this release. I’ve been working on Rails for more than 7 years and the quality of the framework we have today is just astounding. This is only possible as a community effort and Rails 3 has seen so many incredible developers step up and help make this our best release ever (wink). Many thanks to all of you.

We’ll continue to develop Rails 3.0 with fixes and tweaks via the stable branch and Rails 3.1 is already cooking on master.

UPDATE: We’re raising money for Charity:Water in the name of Rails 3.0. Please donate and help us bring clean water to 5,000 people in the name of the Rails community.

Rails Has Great Documentation

To this day I still hear people complain that Rails has poor documentation. From where I’m sitting this seems far from the truth. Let me lay out the evidence piece by piece:


RailsTutorial.org

To learn Rails from scratch Michael Hartl recently finished his book Ruby on Rails Tutorial: Learn Rails by Example. The book teaches Rails 3 from the ground up and it’s available for FREE online. If you’d rather have a PDF or a book you can grab that as well (and he’s even working on some screencasts).

The source for the finalized book will be pushed to GitHub and released under a Creative Commons License shortly after Rails 3 is done. If you’d like to help translate the book to your language of choice, feel free to contact Michael and he’ll get in touch when it’s time to make it happen.

Rails Guides

If you’re not a Rails newbie don’t forget about the Rails Guides, which have been updated for Rails 3.

Rails API Docs

There are two main websites I use to do API lookups. The first is Rails Searchable API Doc, which has online and offline searchable documentation. The second is APIdock which is online only, but has the ability to comment and easily compare different versions of documentation.

Rails 3 Free Screencasts

If you’re more of a visual learner (like me) then there are plenty of free screencasts to teach you about Rails 3. About 2 months ago I produced the Rails 3 Screencasts, which will get you started.

Ryan Bates has also produced an incredible amount of Rails 3 screencasts over on Railscasts.com. Ryan has been producing Railscasts for over 3 1/2 years, isn’t that crazy?

There’s also a few good free screencasts over on Teach me to Code by Charles Max Wood.

Keeping on the Edge

If you find yourself wondering how to keep up with all of the newest features / libraries for Rails 3, both the Ruby5 Podcast and the Ruby Show are going strong. Don’t listen to audio? It doesn’t matter, just subscribe to the Ruby5 RSS feed and get links with descriptions to all the newest libraries, tutorials, and more. You might also want to checkout Peter Cooper’s new Ruby Weekly, a Ruby email newsletter.

Need to upgrade a big app to Rails 3?

Jeremy McAnally’s Rails 3 Upgrade Handbook PDF is just $12. There’s also a few paid screencasts for the upgrade over on Thinkcode.tv and BDDCasts.

Need a Book?

There’s a bunch of books that will be coming out after the release, most of which you can start reading now. The Rails 3 Way by Obie Fernandez, Rails 3 In Action by Ryan Bigg and Yehuda Katz, Beginning Rails by Cloves Carneiro Jr and Rida Al Barazi, and of course the Agile Web Development with Rails:fourth edition by Sam Ruby, Dave Thomas, and David Heinemeier Hansson.

In conclusion

No more complaining about lack of good documentation! Seriously. If you want even more Rails 3 content, check out the blog post by Kevin Faustino on 34 Ruby on Rails 3 resources to get you started.

Rails 3.0: Release candidate 2

The release candidate process is progressing as planned. This second candidate has very few changes over the first, which means that unless any blockers are discovered with this release, we’re targeting the final release of Rails 3.0 for this week(!!!).

So please do help us weed out any blockers. Especially in our two new main dependencies: Bundler and ARel. They’ve both progressed into release candidacy for their 1.0 releases and will be sharing the same 1.0-final release date as Rails 3.0.

You can see a complete list of all the dotted t’s and crossed i’s on the new fabulous Github comparo view of RC1 and RC2.

As always, you install this latest version with: gem install rails --pre

Also note that Rails 3.0 now has it’s own stable branch. The master branch is now reserved for Rails 3.1 development. (That’s right, we’re already going there and it’s going to be M-A-G-I-C-A-L!).

Rails 3.0: Release candidate!

High off Baltimore Pandemic and Yellow Tops, I believe we promised a release candidate shortly after RailsConf. As things usually go in open source, we gorged ourselves on fixes and improvements instead. But all to your benefit. We’ve had 842 commits by 125 authors since the release of the last beta!

Now it’s time to just say good is good enough, otherwise we could keep on with this forever. So please welcome the Rails 3 release candidate! You install, as always, with gem install rails --pre.

Most of the fixes have been of minor significance, but we did manage to dramatically speed up Rails 3 development and startup speed for larger applications (Basecamp went from insufferable to about 2.3 levels of enjoyment).

Speed is now pretty good across the board except for part of Arel that Active Record now depends on. We’ll be making sure we get performance of Active Record back to at least 2.3 levels before release.

A few more highlights:

Indulge yourself in the delights of all the glorious details from the commit logs or checkout the slightly less pedantic summaries in the CHANGELOGs.

This release candidate of Rails 3 also concides with the release candidate of Bundler 1.0. Huge strides were made with Bundler and it should both be much faster and have most of the edge cases sawed off.

I’ve said “we’re almost there” so many times that I’m almost exhausted. But really, guys, WE’RE ALMOST THERE!!!1

1 Just a few weeks before final is out?

Rails 3.0: Beta 4 now, RC in days

RailsConf 2010 is underway and what better occasion to do the final stage of the Rails 3 beta program. We’re very pleased to announce Rails 3 beta 4, which we’ll be hammering on and tuning during RailsConf.

At the end of RailsConf, we’ll be putting out the release candidate. So if you’re at the conference, and even if you’re not, now is the time to give upgrading a chance or even starting a new app. We’re all responsible for making this release solid, please join the fun.

You can install the latest beta with gem install rails --pre

Since we’re so close to release now, it’s also a great pleasure to introduce the new Rails 3 screencast series by Gregg Pollack and EnvyLabs. They’ve done an awesome job putting together six episodes and more are coming. You can also read along in their great Rails 3 slides from the RailsConf tutorial.

I also gave a keynote on Rails 3 this morning at RailsConf, so you can enjoy the slides.

Let’s race to the finish line together.

Ruby on Rails 2.3.8 Released

The 2.3.7 release slipped out the door too hastily. Fixing compatibility with the rails_xss plugin inadvertently forced everyone to use it. Facepalm.

I apologize for wasting a chunk of your day on installing what ought to have been a patch-level update only to find it breaks your app. That’s well out of line with our stable release process and it’s my fault for stepping out of it. I got caught up in a sky-is-falling response to a 2.3.6 bug that affected a handful of users and responded with a fix that exposed a new flaw to nearly all users, despite testing and sanity checking.

Thanks for all your feedback today. We hear you, and yes, a thousand times yes. Every stable release, including point releases, deserves the same methodical drumbeat on its march from git stable to to .pre gem to final gem. Expect no less.

Now, on to the gem-cutting: Rails 2.3.8 is available now, bringing us back to stable ground.

Ruby on Rails 2.3.7 Released

With the 2.3.6 release hot out of the oven, Nathan Weizenbaum began updating HAML to support it. He uncovered a couple of bugs in the HTML-safety changes backported from Rails 3, so we’re cutting a 2.3.7 release to fix them.

If you use the rails_xss plugin for automatic HTML escaping, you should upgrade to Rails 2.3.7 and the latest rails_xss plugin.

If you don’t use the rails_xss plugin yet, now’s the time to start. It’s baked in to Rails 3.

Update: fixing compatibility with the rails_xss plugin broke HTML-safety for apps that don’t use rails_xss. We’re sorry, all: HTML-safety is meant to be opt-in! The fix is available now in 2.3.8.pre1 and will be released shortly.

Ruby on Rails 2.3.6 Released

We’ve released Ruby on Rails 2.3.6: six months of bug fixes, a handful of new features, and a strong bridge to Rails 3.

We deprecated some obscure and ancient features in Rails 2.3.6 so we could cut them entirely from Rails 3. If your app runs on Rails 2.3.6 without deprecation warnings, you’re in good shape for a smooth sail onward.

This slow-cooked dish is brought to you some 87 committers from our all-volunteer kitchen.

Now, let’s open the goodie bag!

Action Pack

  • Upgrade Rack from 1.0.1 to 1.1.0.
  • XSS prevention: update to match Rails 3 and move to the official plugin at http://github.com/rails/rails_xss.
  • Cookies: convenient cookie jar add-ons to set permanent or signed cookies, or both at once: cookies.permanent.signed[:remember_me] = current_user.id. Read more.
  • Flash: promote alert and notice, the most common flash keys in many apps, to self.alert = '...' and self.notice = '...'. Add redirect_to url, :alert => '...' and :notice => '...'. Read more.
  • i18n: localize the label helper.

Active Record

  • Namespacing: support optional table name prefixes on modules by defining self.table_name_prefix. Read more.
  • Destroy uses optimistic locking.
  • Counter cache: use Post.reset_counters(1234, :comments) to count the number of comments for post 1234 and reset its comments_count cache.
  • PostgreSQL: always use standard-conforming strings, if supported.
  • MySQL: add index length support. Read more.
  • MySQL: add_ and change_column support column positioning using :first => true and :after => :other_column.

Active Support

  • Upgrade i18n from 1.3.3 to 1.3.7.
  • Upgrade TZInfo from 0.3.12 to 0.3.16.
  • Multibyte: speed up string verification and cleaning.
  • JSON: use YAJL for JSON decoding, if available. gem install yajl-ruby
  • Testing: add assert_blank and assert_present. Read more.
  • Core: backport Object#singleton_class from Ruby 1.8.8, deprecating our Object#metaclass.
  • Core: add Object#presence that returns the object if it’s #present? otherwise returns nil. Example: region = params[:state].presence || params[:country].presence || 'US'
  • Core: add Enumerable#exclude? to match include?.
  • Core: rename Array#rand to Array#random_element to avoid collision with Kernel#rand.
  • Core: rename Date# and Time#last_(month|year) to #prev_(month|year) for Ruby 1.9 forward compatibility.

Active Resource

  • JSON: set ActiveResource::Base.include_root_in_json = true to serialize as a hash of model name → attributes instead of a bare attributes hash. Defaults to false.

Action Mailer

  • Upgrade TMail from 1.2.3 to 1.2.7.

Railties

  • Silence RubyGems 1.3.6 deprecation warnings.

Peruse the commit log for the full story.

Community Highlights

It’s that time again, to summarize a few interesting Rails links to highlight some of the best of the community. All of these were initially covered on the Ruby5 Podcast, the twice weekly Ruby newscast.

Rails 3 Content

The next Rails3 Bugmash is taking place May 15th and 16th. If you’ve never contributed to Rails, this is your chance to give back a little and do your part to make Rails 3 the best version ever.

To get a complete picture of routes in Rails 3, Rizwan Reza covered it best in an article over on the Engine Yard blog. If you dig the Engine Yard Rails 3 content, they recently created Rails Dispatch, where they have articles and screencasts published weekly.

Alex Maccaw recently used the Rails 3 ActiveModel abstraction to build an ActiveRecord-like in-memory database called Supermodel. You get all of the ActiveRecord goodness, such as validations, callbacks, and observers, but with none of that database headache.

As you may already know, the arel library from Rails 3 gives us a great new syntax for creating queries. Under the covers, arel converts your where conditions into sql is by using something called a PredicateBuilder. Ernie Miller recently put out a plugin called MetaWhere that takes advantage of these PredicateBuilders to give arel even more functionality.

Lastly, if it’s still not clear to you how awesome bundler is, go read Yehuda’s recent post on the topic.

Authorization

Do you ever find the need to access current_user in your models? This is often required when you’re logging model/table changes on a per user basis. There are many hacks to accomplish this, but David Bock has a gem called SentientUser which does this a little cleaner.

Once your websites goes big and you start to worry about malicious user attacks, you may want to take a look at Arto Bendiken and Brendon Murphy’s Rack::Throttle Middleware. Throttle does just want you think it does, allowing you to limit the number of requests a user can ping your site (per second).

Lastly, Ryan Bates released version 1.1 of CanCan, his authorization and permission library that allows you to restrict what your users can do throughout your application.

Service Libraries

You may have heard that the Facbook API is now adopting OAuth2. If you’re ready to jump in, Michael Bleigh released the OAuth2 gem just last week.

Rails makes a great RESTful backend for iPhone applications, and recently Anthony Moralez created APN_on_rails which makes it super easy to do Apple Push Notifications.

There’s no need to reinvent the wheel if your Rails application needs e-commerce, this is where the Spree gem comes in, which recently hit version 0.10.0, containing a bunch of new features.

Testing

Does your Rails application have a monster testing library that takes forever to run? Then it may be time to take a look at Hydra by Nick Gauthier, a distributed testing framework which allows you to run your tests in parallel locally or across remote servers.

Some people think cucumber can be too verbose for integration tests (which clients may never read). If you think cucumber is for vegetarians, then perhaps it’s time to taste some Steak by Luismi Cavalle. Steak is a small library which helps you generate quick and clean acceptance/integration tests using RSpec.

Talking about RSpec, there are some new conventions out there to clean up your old RSpec code. If you haven’t started using “Let”, then it may be time to look through a few of Jon Larkowski’s slides.

Additional Useful Libraries

If you ever find yourself with odd memory issues then it’s probably time to use memprof.com, a new web service by Joe Damato and Ruby Hero Aman Gupta. Memprof allows you to collect memory usage information from a Ruby process and immediately upload and view it using an intuitive web interface.

Rails applications are often full of forms, and sometimes you even need to give your clients the ability to create different types of forms or surveys. This is where the Census gem comes in, providing an admin interface for creating forms, and even the ability to search through the results.

To wrap things up, delayed_job recently hit 2.0, and you’ll want to upgrade if you have an older version. The new version has some performance improvements and adds support for non-ActiveRecord ORMs.

Additional Content

To keep track of Ruby conferences check out Ruby There, a listing of all the upcoming conferences and even when the Call for Proposals are due.

For more news and libraries check out the Ruby5 podcast. If you don’t usually listen to audio, you can just subscribe to the RSS feed which contains a summary of everything covered.

If you have any stories/libraries you’d like to spread the word about, feel free to email ruby5@envylabs.com and we’ll at least get you covered on the podcast. Thanks!

Image Credit: Blue Sky on Rails by ecstaticist, Analog Solutions 606 Mod by Formication, Rainbow by One Good Bumblebee. Orange County Security by henning, remember by tochis, Darwin Was Right About Media Players! by Neeku, remote controls by redjar.

This post has been translated into Belorussian provided by PC

Rails 3.0: Third beta release

We’re marching towards the release candidates with hurried steps, but along the way we stopped by for another beta. This one spins out a few overdue extractions into plugins (see http://github.com/rails/verification and http://github.com/rails/dynamic_form), fixes a security issue with cookies, crosses a few t’s and dots a few i’s. Upgrading from beta 2 is recommended.

As always, you can install the latest beta with gem install rails --pre.

We’ll see you again soon for the release candidate.