This Week in Edge Rails

February 14, 2009 – February 27, 2009

The sharp-eyed will notice that This Week covers two weeks this week. As Rails 2.3 approaches release, the core team is getting pickier about what goes into the source code, and is concentrating on fixing bugs. You can expect to see Rails 2.3 RC2 very soon, and that may be the last release candidate. So if you haven’t tested your own applications on Rails 2.3 yet, it’s time to do so. The edge code is generally stable right now, so it’s a great time to take a look.

Batch Processing

You can now process large numbers of records from an ActiveRecord model with less pressure on memory by using find_in_batches:

Customer.find_in_batches(:conditions => {:active => true}) do |customer_group|
  customer_group.each { |customer| customer.update_account_balance! }

You can pass most of the find options into find_in_batches. However, you cannot specify the order that records will be returned in (they will always be returned in ascending order of primary key, which must be an integer), or use the :limit option. Instead, use the :batch_size option, which defaults to 1000, to set the number of records that will be returned in each batch.

The new each method provides a wrapper around find_in_batches that returns individual records, with the find itself being done in batches (of 1000 by default):

Customer.each do |customer|

Note that you should only use this method when you have enough records to justify batch processing: for small numbers of records (less than 1000), you should just use the regular find methods with your own loop.


A Note About Template Loading

After some extensive work by several authors (here’s the Lighthouse ticket), Rails 2.3 includes the ability to enable or disable cached templates for any particular environment. Cached templates give you a speed boost because they don’t check for a new template file when they’re rendered – but they also mean that you can’t replace a template “on the fly” without restarting the server.

In most cases, you’ll want template caching to be turned on in production, which you can do by making a setting in your production.rb file:

config.action_view.cache_template_loading = true

This line will be generated for you by default in a new Rails 2.3 application. But please note: if you’ve upgraded from an older version of Rails, you won’t have this setting in your production.rb and template caching will be off by default. Unless you really need the ability to update templates in production without restarting the server, you should be sure to add this setting when you upgrade.

2009 Ruby Hero Awards

There are many people in the Ruby community who contribute to our blossoming ecosystem. Some do this by producing educational content and others by contributing to open source libraries or helping out newcomers to the Ruby language. Every week I do my best to help promote the work of these people by talking about the most interesting bits on the Rails Envy Podcast. However, sometimes it just doesn’t seem like enough.

There are some developers who contribute to the community above and beyond the others. These people don’t always get the recognition they deserve, which is why last year I put together the Ruby Hero Awards. Hundreds of people submitted nominations and at RailsConf 2008 we gave away 6 awards to people in our community who deserved a round of applause.

Last year we gave awards to Ryan Bates, Yehuda Katz, Ilya Grigorik, Evan Weaver, Tom Copeland, and James Edward Gray II. This year we’re looking for 6 more people to give awards to and we need your nominations to figure out who you think deserves one. Three things to keep in mind here:

  • We’re looking for people who do not get their deserved recognition. For example, any of those Rails Activists and Rails Core members are out of the running.
  • When you submit a nomination you’ll have to enter 25 words as to why you think someone should be nominated.
  • The final 6 award winners will be determined by having the 6 winners from the previous year voting on them. The nominations you submit will certainly play a big factor in this decision, but won’t be the determining factor (this keeps things from turning into a popularity contest). So please don’t post to your blog telling all your friends to “Nominate You”, it ain’t gonna work.

The 6 winners will be announced on stage at RailsConf 2009, which is just around the corner. So if you know someone Ruby or Rails community who deserves some recognition, please take 2 minutes and submit a nomination for them.

Photo Credits: Ruby Hero Awards by Duncan Davidson, IMG_5428 by wyros

This Week in Edge Rails

February 7, 2009 – February 13, 2009

It’s been a fairly busy week on the edge, but there are not a lot of new features to point at. That’s good: at this point in the release cycle, the team is concentrating on nailing down things to be solid even in strange circumstances. This is also the point at which your help is critical: if a change affects one of your applications, and you don’t tell anyone about it, you can’t expect a fix. You don’t need to be running your applications full-time on RC1, but please, check out edge Rails, try it out, and report anything that seems to be broken. Bonus points if you include tests to show the expected behavior, and super bonus points if you submit a patch to go with it.

View Rendering Changes

A series of commits have addressed some issues with view rendering. The end result is to improve the performance of view rendering in development mode, and to bring back template recompiling in production mode (so you can change a view and have the changes show up without having to restart the whole server). Some of this work is ported from rails-dev-boost and if you want to come up to speed on what’s been done here the best thing to do is read the Lighthouse ticket

Partial Scoping for Translations

A change to the translation API makes things easier and less repetitive to write key translations within partials. If you call translate(".foo") from the people/index.html.erb template, you’ll actually be calling I18n.translate("") If you don’t prepend the key with a period, then the API doesn’t scope, just as before.


Nested Attributes API Change

The API for NestedAttributes has been changed so as to work better with existing associations. If you’ve just used this for nested model forms, the changes will probably be transparent to you, but if you’ve been deeper into the internals you should have a look at the discussion in Lighthouse as well as the code in the commit.


Less Brittle Tests for Scaffolded Controllers

The automatically-generated functional tests for controllers generated with script/generate scaffold now use to_param instead of id to identify records, which should make them more resilient to changes in fixtures over time.


TimeWithZone changes

There were some internal changes to TimeWithZone that make its code more readable and efficient. One change surfaces to the API: TimeWithZone#to_formatted_s is an alias for TimeWithZone#to_s.


A New Inflection

Breaking a long-standing policy, there was actually a change to the built-in list of pluralizations this week: Rails now handles database/databases correctly. Remember, a foolish consistency is the hobgoblin of little minds, and please don’t take this as an invitation to reopen the old ticket 10919. The policy remains that you can add inflections in your own application’s initializers if you need to do so.

The State of the Wiki

The new and revitalized Rails Wiki launched about two weeks ago, so it’s time for a progress report back to the Rails community. The short answer: things are going well. We’ve had nearly a hundred edits, dozens of topics put in place, and an active discussion on the wiki mailing list. Translators are already at work making the wiki content available in multiple languages. For topics ranging from a first Rails application walkthrough to handling timezones, the new wiki is already a spot to go for quality Rails content.

The wiki team has applied lessons learned from the old Rails wiki, which has gone from being a comfortable spot to find out a few things to a cluttered mess over the years. They started out by defining an overall structure and figuring out what warranted coverage in the wiki. Then they protected a few pages from edits and set up a login system to encourage accountability. The result, so far, is a very promising start at an information resource that can benefit all Rails developers.

But there’s plenty more to do. If you take a look at the new wiki home page you’ll find a bunch of topics in red with dashed underlines. Those are topics that we want, but that no one has written yet. If you have a few minutes to give back to the community, why not drop by? Whether it’s drafting a new topic from scratch, revising an existing topic to be more clear or correct, adding links to high-quality external resources, or translating the wiki into another language, there’s plenty left to do – and just about every Rails developer should be able to contribute.

This Week in Edge Rails

January 31, 2009 – February 6, 2009

The big news in edge Rails this week, of course, is the release of Rails 2.3.0 RC1. There’s been a fair amount of activity in the days since that happened, much of it concerned with tidying things up and fixing bugs based on early adopter issues and feedback. Thanks for all the testing, and by all means keep it up!

Nested Form Support in Active Record and Action Pack

This one is big enough that it got a whole blog entry of its own (the version that was committed has minor changes from what you’ll see there). There are two main parts to this commit. First, Active Record can now update the attributes on nested models directly, provided you tell it to do so:

class Book < ActiveRecord::Base
  has_one :author
  has_many :pages

  accepts_nested_attributes_for :author, :pages

Turning on nested attributes enables a number of things, including automatic (and atomic) saving of a record together with its associated children, and child-aware validations. But the big visible one is nested form support. Provided the parent model accepts nested attributes for the child objects, you can create nested forms using form_for and field_for. These forms can be nested arbitrarily deep, allowing you to edit complex object hierarchies on a single view without excessive code. For example, given this model:

class Customer < ActiveRecord::Base
  has_many :orders

  accepts_nested_attributes_for :orders, 
    :allow_destroy => true

You can write this view in Rails 2.3:

<% form_for @customer do |customer_form| %>
    <%= customer_form.label :name, 'Customer Name:' %>
    <%= customer_form.text_field :name %>

  <!-- Here we call fields_for on the customer_form builder instance.
   The block is called for each member of the orders collection. -->
  <% customer_form.fields_for :orders do |order_form| %>
        <%= order_form.label :number, 'Order Number:' %>
        <%= order_form.text_field :number %>

  <!-- The allow_destroy option in the model enables deletion of
   child records. -->
      <% unless order_form.object.new_record? %>
          <%= order_form.label :_delete, 'Remove:' %>
          <%= order_form.check_box :_delete %>
      <% end %>
  <% end %>

  <%= customer_form.submit %>
<% end %>

For more information, see Ryan Daigle’s excellent What’s New in Edge Rails: Nested Object Forms.


Rails Guides Rework

The Rails Guides have switched from using AsciiDoc markup to using Textile markup. This has a couple of benefits: first, it makes it easier to contribute to a guide. Second, it means that we can dispense with the compiled HTML versions of the guides in the Rails tree, because we can assume any developer can build from Textile. There’s a spiffy new look for the Guides web site too – check it out at the beta site.


Scaffolding Changes

There were some cleanups to the code produced by script/generate scaffold – nothing too major, but they bring the controller and views more into line with current Rails best practices. Along the same lines, the “Riding the Rails” index.html page generated in new Rails applications now includes a link to the Rails Guides.

commit commit commit

This Week in Rails 3.0

Now that Rails 2.3 has hit the release candidate phase, some of the development effort is turning to Rails 3.0. With that activity heating up, it’s time to start keeping you all informed as to happenings on the 3.0 version of the Rails source. I’ll still be posting separate “This Week in Edge Rails” information focused on Rails 2.3, so you can keep straight which changes are ready now and which still lie in the relatively distant future.

The Vision

The Rails 3 vision is based on the announcement that was made in December: we’re bringing in the key ideas from Merb to Rails, including:

  • A more modular Rails core, so you can run applications with less than the full Rails stack
  • Performance optimizations
  • Framework agnosticism with sensible defaults
  • A tested and documented API for extensions

Rails 3 promises to substantially advance the state of the art in Ruby web frameworks, while still providing migration paths from Rails 2.x and Merb 1.×.

The Source Code

The Rails 3.0 branch in the main Rails project on GitHub is the place to be to see what’s going on:

git clone git://
git checkout 3-0-unstable

As the branch name might tell you, this is still a fairly experimental place to be: you probably don’t want to roll this out for production applications just yet. But it is tested code (and it’s using continuous integration to stay that way), and it already includes substantial changes from Rails 2.x thanks to the efforts of Yehuda Katz, Joshua Peek, and others. The changes so far are focused on cleaning up and improving Rails internals, rather than on adding new features.

Action Dispatch

Action Dispatch is a new Rails component which lives in Action Pack (along with Action Controller and Action View). Action Dispatch is responsible for all the processing involved with dispatching requests: request and response handling, HTTP status codes, file uploads, URL and parameter parsing, session storage, and so on.

Action View Reorganization

There are substantial changes in the Action View internals. The overall goal was to clean up a bunch of special cases and extra hooks that had built up over the years, and to leave all callers into Action View using a single unified entry point. The code cleanup has been coupled with some rearrangement of the Action View source to make it easier to find bits of functionality. This was a substantial effort; if you’re interested in a detailed look at the refactoring, you can read up on it at Yehuda’s blog

Callback Optimizations

A new method of handling callbacks removes the need for iterating through the callback list at runtime, and provides a substantial speed improvement in this area of the code. Though this is a micro-optimization that may not have much effect by itself, the hope is that by carefully optimizing as many hot spots as possible we can get a visible overall speedup in page creation and delivery – which, after all, is the point of a web framework.

What’s Next?

Obviously, there’s a long distance between where we are today and the Rails 3.0 vision. We’re fortunate to have an excellent team of core programmers devoting substantial time to making that journey. The interim goal is still to have a beta version of Rails 3.0 out in time for RailsConf in May. You can help in the same ways as with earlier versions of Rails: download the source, start testing it with your applications, and submit your own ideas and patches to the Rails Lighthouse. Rails has been a joint effort of thousands of developers over the years, and Rails 3.0 will be no different in that regard.

Rails Guides Gets a Facelift

There’s a brand new version of Rails coming, as you already know. What better time for a new version of some of the Rails documentation? So the Rails Guides team is pleased to announce a refresh of the Ruby on Rails Guides site, just in time for the Rails 2.3 release.

The most obvious change you’ll see is a new look, thanks to some awesome design work from Jason Zimdars. But the visual refresh isn’t all that’s going on here. We’ve also been working to update the Guides for Rails 2.3, as well as to add new guides to the list.

And there’s good news if you want to get involved too. Behind the scenes, Tore and Pratik switched our markup engine from AsciiDoc to Textile. This makes the Guides easier to write and edit and easier to build into a Rails project. If you’ve got some spare time to help out, join us in the #docrails room on, and help make the Rails Guides into a great resource in time for the 2.3 release.

Calling All Rails-Savvy Designers

One thing that has been a continuing challenge for many Rails developers is finding a good designer to work with. There are certainly plenty of fantastic designers out there, but it’s often difficult to find one who is comfortable working directly in a Rails project.

In an effort to help ease this challenge, and at the behest of some interested developers and designers, the Rails Activists have set up a group for Ruby Graphics Designers. The idea is to have a place for communication: a spot where designers can ask questions about git or erb, or where developers can try to find a designer to work with.

Of course, a group without participation is nothing to crow about. If you’re a developer – or especially if you’re a designer who works with Rails – we’d love to have your participation. If you’re interested in the visual design and information architecture of Rails applications, c’mon by and say hi! And if you have other ideas about how we can encourage closer collaboration between the Rails community and the design community, we’d love to hear them.

Rails 2.3.0 RC1: Templates, Engines, Rack, Metal, much more!

Rails 2.3 is almost ready for release, but this package is so stock full of amazing new stuff that we’re making dutifully sure that everything works right before we call it official.

So please help us do thorough testing of this release candidate. Lots of the underpinnings changed. Especially the move to Rack. So we need solid testing and will probably have a slightly longer than average release candidate phase to account for that.

But boy will it be worth it. This is one of the most substantial upgrades to Rails in a very long time. A brief rundown of the top hitters:

  • Templates: Allows your new skeleton Rails application to be built your way with your default stack of gems, configs, and more.
  • Engines: Share reusable application pieces complete with routes that Just Work, models, view paths, and the works.
  • Rack: Rails now runs on Rack which gives you access to all the middleware goodness.
  • Metal: Write super fast pieces of optimized logic that routes around Action Controller.
  • Nested forms: Deal with complex forms so much easier.

And that’s just the tip of the iceberg. We’ve put together a complete guide for the Rails 2.3 release notes with much more information.

You can install the release candidate with:

gem install rails --source

Enjoy, report the bugs, and let’s get Rails 2.3 final out the door soon.

This Week in Edge Rails

January 24, 2009 – January 30, 2009

This week we saw 35 commits in edge Rails – though many are bug fixes and minor things. Here’s one more preview of some of the recent and significant changes.

Localized Views

Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a Posts controller with a show action. By default, this will render app/views/posts/show.html.erb. But if you set I18n.locale = :da, it will render app/views/posts/show.da.html.erb. If the localized template isn’t present, the undecorated version will be used. Rails also includes I18n#available_locales and I18n::SimpleBackend#available_locales, which return an array of the translations that are available in the current Rails project.


Reconnecting MySQL Connections

MySQL supports a reconnect flag in its connections – if set to true, then the client will try reconnecting to the server before giving up in case of a lost connection. You can now set reconnect = true for your MySQL connections in database.yml to get this behavior from a Rails application. The default is false, so the behavior of existing applications doesn’t change.


Easier Testing for JDBC

To make life easier for anyone using Rails on JRuby, Active Record now includes test tasks for a bunch of database accessible via JDBC: Derby, H2, hsqldb, MySQL, PostgreSQL, and sqlite3 (the latter three are also available through non-JDBC connections, as you know). You need to have the database, the activerecord-jdbc-adapter gem installed, and the specific activerecord-jdbcdatabase-gem for the database you’re testing. Then you can run tests like this: jruby -S rake test_jdbcmysql (with similar tests for the other adapters, of course).


HTTP Digest Authentication Support

This one first appeared a couple of weeks ago, but was reverted due to some problems with the initial implementation. Fortunately, the problems were resolved, and Rails 2.3 will ship with built-in support for HTTP digest authentication. Ryan Daigle published some sample code.


grouped_options_for_select Helper Method

Action View already has a bunch of helpers to aid in generating select controls, but now there’s one more: grouped_options_for_select. This one accepts an array or hash of strings, and converts them into a string of option tags wrapped with optgroup tags. For example:

   ["Baseball Cap","Cowboy Hat"]]], 
   "Cowboy Hat", "Choose a product...")


 <option value="">Choose a product...</option>
 <optgroup label="Hats">
   <option value="Baseball Cap">Baseball Cap</option>
   <option selected="selected" value="Cowboy Hat">
     Cowboy Hat