Getting Things Done with Active Record

Mike Clark has a great article on how to dig deeper into Active Record by using acts_as_nested_set and find_by_sql. On the notion of using SQL in an OO model, he writes:

Some may think this breaks object purity. I think it’s just productive. After all, I know there’s a database under there, and SQL is incredibly powerful for querying relational data. Most of the time I’d rather not write SQL because I’m doing CRUD operations. In those cases, Active Record intervenes to boost my productivity. And when SQL is the best tool for the job, Active Record gets out of the way to let me be most productive.

I couldn’t agree more. SQL is not bad at all. Once you take out the repetition for the simple cases, you’re left with a very powerful query language for the hard cases.

Rails 0.13: 225+ features/fixes in 75 days!

After the longest gap between releases since Rails was made public and after more than 225 fixes and new features, the final major release before the 1.0 milestone has arrived. We’ve basically put in three new features or fixes every single day for the past 75 days. But what do you care about our labouring efforts? Here’s what’s new in 0.13.0:

Ajax: Visual effects, drag’n’drop, sortable lists, auto-completing text fields
Thomas Fuchs is the latest member of the Rails core contributor group and his amazing set of Javascript magic, entitled, has been integrated in this release.

It adds a completely rewritten visual effects engine, drag-and-drop capability including sortable lists, and autocompleting text fields to Rails. All building on top of Prototype, the foundation for Ajax in Rails, which has also received a spiffy upgrade by Sam Stephenson.

Hand in hand with the Javascript files is a fresh batch of helper methods that enables to skip the process of writing any Javascript yourself. The new auto_complete_for macro is one of these helpers and it makes adding Google Suggest style auto-completing text fields effortless, as does sortable_element for sortable lists and floats and draggable_element and it’s counterpart drop_receiving_element for drag-and-drop. Try out the live demos and see source code.

We also have Ajaxified progress indicators for file uploads in as an experimental feature in this release. It makes for a much more user-friendly experience uploading large files. See the demo. It’s experimental nature means that it only works on Apache, lighttpd 1.4.x, and only in some environments. Consider it a preview of really cool tech. You need to include ActionController::Base.enable_upload_progress in your environment.rb file to turn it on.

We’ve additionally added support for graceful error handling of Ajax calls:

      :url => { :action =>"faulty" },
      :update => { :success =>"good", :failure =>"bad" },
      403 =>"alert('Forbidden- got ya!')",
      404 =>"alert('Nothing there...?')",
      :failure =>"alert('Unkown error ' + request.status)")

And if you want to perform multiple document updates on a single Ajax call, there’s now the lovely JavascriptHelper#update_element_function, which can be used to generate a stacked return.

Migrations: Agile software needs agile databases
Migrations can manage the evolution of a schema used by several physical databases. It’s a solution to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to push that change to other developers and to the production server. With migrations, you can describe the transformations in self-contained classes that can be checked into version control systems and executed against another database that might be one, two, or five versions behind.

They currently only work with MySQL and PostgreSQL, but with the help of the community, we’ll hopefully have most databases supported in upcoming releases. Read more in the Migration documentation.

Performance: Faster routes, faster everything!
One of our primary goals with this release is to identify and address performance issues. Stefan Kaes took on the task of optimizing the entire code base and contributed numerous speedups with additional help from Jeremy Kemper. An entire rewrite of Routes by Nicholas Seckar makes it nearly seven times faster now. And all this comes with complete backwards compatability. In an effort to make developers more performance-aware, you can now use the new BenchmarkHelper to measure the execution time of a block in a template.

Sweepers: Clean up your caches in a single sweep
ActionController::Caching::Sweeper is a new approach to sweeping caches that follows a much more intuative one-sweep system where the caches are actually cleared on the observer callbacks. Not just recorded to be cleared during a later filter callback. Sanity is restored to sweeping.

Rendering: One method to bind them all
In the wake of refactoring Active Record’s find API, the various render methods got a whole new suit, making the render method the single point of entry for all rendering tasks. Tobias Luetke has a good before and after write up of how render is used now.

Lessons learned from find and render: Consolidate multiple method names that do similar things into one method, use symbols to dictate what used to be done by method name and parametrize with an options hash rather than positional parameters.

Read more about it on the new API documentation for render.

FastCGI: Easier to update, more stable in the running
With a new release of a better and up to date FastCGI Ruby binding, and as FastCGI becomes solidified as the deployment mechanism of choice, it’s a good time to have a vastly improved dispatch.fcgi with changes that include:

  • Send HUP to force the fcgi process to dynamically reload the application
  • Send USR1 to force the process to gracefully restart (allowing active requests to finish first)
  • Better crash logging

We’ve also extracted a RailsFCGIHandler, so you in the future can update Rails and get improvements without having to get a fresh dispatch.fcgi file.

Routes: Giving them a name and calling them by it
On top of Nicholas Seckar’s entire rewrite of the Routes code come Named Routes by Marcel Molina. Named Routes allow you to reduce code duplication by associating a name with a given route rule. This generates a convenience method that wraps the route rule hash. You define a named route by calling it in your routes.rb in place of the connect method. So, for example:

  map.home '', :controller => 'main', :action => 'start'

So with the above named route, what would have previously been

  redirect_to :controller => 'main', :action => 'start'

is now

  redirect_to :home_url

Parametrize your routes. With:

  map.user_page 'users/:user', :controller => 'users', :action => 'show'

You could do

  link_to @user.username, user_page_url(:user => @user)

See more at the Named Routes wiki page.

Email attachements: Make those emails carry the load
Action Mailer now supports sending attachments and multipart messages. Jamis Buck has been leading the way to making ActionMailer robust and feature complete. There’s a fresh new API too that gives specifying emails a more domain-language feel to it. Read all about it in Action Mailer API.

Validations: Run them conditionally and only if
With the new :if option for all validations, you can limit when an attribute is validated, either using a block or a method reference. Examples:

  1. Conditional validations such as the following are made possible:
    validates_numericality_of :income, :if => :employed?
  1. Conditional validations can also solve the salted login generator problem:
    validates_confirmation_of :password, :if => :new_password?
  1. Using blocks:
    validates_presence_of :username, :if => { |user| user.signup_step > 1 }

Fully backwards compatible!
As has been the norm since around 0.9.0, this release is mindful of backward compatibility, so despite the flow of fixes, improvements, and features, your existing applications won’t need to be updated code-wise. All you need to do to upgrade is get the new gems with gem update rails and then generating the new infrastructure files with rails <your-app-dir>.

You want to overwrite the dispatches, the prototype library, the Rakefile, and the test_helper.rb. Don’t overwrite application_controller.rb, application_helper.rb, or other files you may have tailored, though. It’s always good to do this run on a backup first and check that every things work.

Last major stop before 1.0!
First I want to congratulate the core contributor team on the amazing accomplishment that is this release. The group came together in a stronger-than-ever force especially for the last few weeks up to release. And as the latest member of the group, Thomas Fuchs deserves special praise for giving Rails such a boost of Ajaxiness with and the associated helpers. It’s incredible that Rails is home to both Prototype and — the two strongest Javascript libraries for Ajaxians around — and Thomas and Sam deserve much lavish praise for making it happen.

Another shout out for Nicholas Seckar. The second-most recent addition to the group. He has once again delivered goodness all over the code base. From named routes to all those little fixes that makes 0.13 a much more solid experience. You tha man.

And all the hard work is paying off. We’re planning to make 0.13 the last major release before 1.0! We might well see 0.13.1 (but hopefully not 0.13.2) before we start pumping out release candidates for the big one-oh, but it’s getting close. Real close, now.

What you’ve seen here is of course only a tiny sliver of the massive amount of new features and fixes. For the full scoop be sure to devour the changelogs:

Enjoy Rails 0.13!

Not knowing where it hurts in ASP.NET

Demetrius Nunes is feeling the pain of going back to maintenance on an ASP.NET project after spending considerable time in Ruby on Rails. He writes about why there might not be more ASP.NET developers looking around for a replacement. When you don’t know where it hurts (or even if it does at all), it’s hard to contemplate improvement:

The main problem here is that until you have the actual experience of working with a good framework like Rails to ease your pain, you don’t feel the pain at all! Or maybe you do feel it, but you just don’t know where it hurts. And to make matters worse, there are very few people that do things differently from you, so you just convince yourself that’s just part of the work.

Traditional ASP.NET development means coding everything on your own, following some of the .NET industry “best practices” promoted mostly by Microsoft – their blueprint examples all do things ‘traditionally’, and then you assume to be the best way to do it. That includes writing stored procedures for every tiny database mangling you need to do and using Datasets and their brothers and sisters for carrying data over the layers, and so on. Object-relational mappers? Who needs them, right? WRONG!

He also recommends a couple of approaches to do if you for some reason have to do ASP.NET and can’t do Ruby on Rails.

'These folks have their priorities all wrong'

Brian McCallister is frustrated that Ruby on Rails is taking away his joyful life as a tool smith. Always creating new libraries and frameworks. Now with all that stuff taken care of, he’s left having to do the actual work:

Along comes RoR, now I find myself having to bear down and implement the actually business functionality for the application. Now it is “implement a SOAP/HTTP service to allow the Swing client to post back its offline changes” and “build an arbitrarily queryable entity-change audit report.” This is no fun compared to writing a config file parser or persistence abstraction layer that can transparently swap out any number of relational databases, orm frameworks, ldap backends, or transaction log based in-memory systems!

That’s bad news when you’re a self-professed “library and framework writing junky”. At least he gets to talk about it. Brian is doing a session at ApacheCon Europe later this month entitled Cheap, Fast, and Good: You can have it all with Ruby on Rails.

Have a great conference, Brian!

\'You\'re probably sick of hearing this\'

Luke Sutton can’t help but share his recent discovery:

OK look, I don’t wanna seem like a total fan-boy and I know the hype has been almost too much. I know you’re probably sick of hearing this and I know you are probably a bit dubious — sceptisim is an admirable trait. I really really really have to say this though; Ruby on Rails totally kicks arse.

Rails Day winners have been found

The 24 hours allotted to create an interesting Rails application from scratch yielded a ton of create entries to Rails Day. The three winners have now been declared, along with the three runner-ups, and honorable mentioning. Congratulation to the winners and to all who completed an application for Rails Day. Everyone learning Rails wins too as all entries are available with full source code.

'Agile development seems natural'

Joe O’Brien is teaching Ruby on Rails to the consultants at his company and is especially enjoying how the language and framework two-pack makes agile development so natural:

Ruby and Rails have captured my heart and mind, not only because of the simplicity of the language itself, but also because of how much easier I can use agile development techniques without feeling as if I’m doing something outside the norm. No, I’m not saying agile development with Java is impossible, but I’m saying with Ruby and Rails, agile development seems natural, and almost a part of the language.

We call that “best practices by invitation”. By generating test stubs, having wiring for mocks ready to be dumped in, following a consistent directory structure all makes it easier to do the right thing. Less chores, more benefits.

Rico does scrolling table on top of Prototype

Sam Stephenson and I met the Sabre team at the O’Reilly/Adaptive Path Ajax Summit a few months back. Their presentation of a scrolling table was part of their very nice line-up of widgets build on Ajax. Talking with Bill and Darren, we got speaking about cooperation, which has now lead to their framework called Rico being build on top of Prototype.

And now they have their LiveGrid widget ported to this framework that let’s you build long lists of endless scrolling (thousands of results without paging). They got an example with Yahoo Search and one with a plain data table. They currently only work in Firefox and IE, so no Safari (but that’s gotta be coming as Bill switched to the Mac at home).

Bill has a long post entilted Death to Paging! – Rico LiveGrid Released that further explains the workings of the widget. Good stuff, guys. Keep it coming.