This Week in Rails (July 11, 2008)

Welcome to the third edition of This Week in Rails, a weekly report with highlights from the Rails community. My apologies for the delay of this post, the past two weeks have been pretty crazy, so this edition covers the most interesting articles and news from the past two weeks.

Let’s kick off this report with a couple of maintenance releases by Jamis Buck. Both Capistrano 2.4.3 and Net::SSH 2.0.3 were published two weeks ago. If you use them, consider upgrading.

Rails 2.1 has been out for a while now, but in case you didn’t have a chance to catch up yet, this post collects several links to useful resources which will help bring you up-to-date.

The Pathfinder Development’s blog put out three highly interesting posts. The first is More Named Scope Awesomeness by Noel Rappin, while the second and third ones are Pretty blocks in Rails views and DRYing up Rails Controllers: Polymorphic and Super Controllers, both by Josh Symonds. Another good (and quick) recent read about controllers, was "MVC: How to write controllers ":http://andrzejonsoftware.blogspot.com/2008/07/mvc-how-to-write-controllers.html.

The same Noel also published the second part of “Developing iPhone applications using Ruby on Rails and Eclipse” for DeveloperWorks (part 1
and 2).

FiveRuns released a valuable gem called data_fabric which adds support for sharding and replication to Active Record. The same company also has a contest up and they’re offering two free tickets to RailsConf Europe in Berlin. Speaking of conferences, Fabio Akita announced that there will be a Rails Summit Brazil 2008 this coming October in São Paulo. This will be the first event of its kind for the Rails community in South America.

An improved version (i.e. 1.1.1) of the Oracle enhanced adapter was released, as well as version 0.9.5 of the IBM_DB adapter for DB2 and Informix, which adds support for Rails 2.1.

In purely chronological order, I found the following articles to be worth pointing out: Speed up slow Rails development in vista – a handy tip for developers using Vista, Adding Google Maps To Your Rails Applications, Live fulltext search in Ruby on Rails and Useful Flash Messages in Rails.

The Railscasts website published two new episodes, one on testing through Selenium, and another on semi-static pages.

Finally, let’s close this edition on a lighter note. The next time you are about to create an acts_as_an_evil_genius plugin or other imaginatively named one, think about this post. ;-)

If you’d like to read more updates from the Ruby side of things, please head over to This Week in Ruby.

Living on the Edge (or what's new in Edge Rails) #3

There hasn’t been much of note in terms of big changes or features in edge Rails lately, so this time I’ll leave you to pore over the Rails commit logs for any bug fixes or minor changes that I haven’t pointed out. There has been some work in progress with ActionPack refactoring and multithreading work as well as some activity in ActiveModel too, but nothing really concrete yet (still very much a work in progress).

As usual, be sure to leave any suggestions and criticisms in the comments.

Thin support with script/server

script/server now checks for the availability of Thin and uses it. Pretty convenient if you are using Thin as your production server (and want to run the same when developing). You’ll have to add config.gem 'thin' to your environment.rb first to get this to work.

This patch was contributed by one of the guys at fluxin.

Changeset

String#humanize can be customized via inflection rules

The String#humanize core extension method is used convert strings with underscore, usually table column names, in them to pretty readable text. For example,

"actor_salary".humanize
=> "Actor salary"
"anime_id".humanize
=> "Anime"

Sometimes this doesn’t work out so well though, when you have legacy tables or simply “inhumanely” named column names like “act_sal_money” (which is really “Actor salary”, but would be #humanize-d to “Act Sal Money”).

You can now specify custom inflection rules (just like you would for plural/singular/irregular/uncountable inflection rules):

Inflector.inflections do |inflect|
  inflect.human /_cnt$/, '\1_count'
  inflect.human 'act_sal_money', 'Actor Salary'
end

Notice how you can also use a regular expression above to convert columns like “click_cnt” to “Click count”.

Thumbs up to Dan Manges and Pascal Ehlert for this patch.

Changeset

Allow conditions on multiple tables to be specified using hash.

Pratik has committed a tiny (but really useful) change to ActiveRecord that allows you to specify conditions on a joined table in its own hash. An example would explain it better:

Anime.all(
  :joins => :character,
  :conditions => {
    :active => true,
    :characters => { :gender => 'female' }
  }
)

The ActiveRecord query above would find all “active” anime with “female” characters.

Changeset

Outro

That’s it for this week’s Living on the Edge – do let me know if you like to see more write-ups on even the minor bug fixes and changes that’d I’d left out this week.

This Week in Rails (June 26, 2008)

Welcome to the second edition of This Week in Rails, a weekly report with highlights from the Rails community.

Ruby Vulnerabilities

As previously reported by Jeremy Kemper, serious vulnerabilities have been discovered for the main Ruby implementations. The official advisory suggests an upgrade path, but there have been several reports of segmentation faults when using Rails with the patched Ruby 1.8.5 and 1.8.6 versions. The Phusion team has published a patch for Ruby 1.8.6-p111, but as things stand now, it hasn’t been included by the Ruby core team (yet).

If you are using Rails 2.1, Ruby 1.8.7-p22 seems the way to go. Unfortunately, Ruby 1.8.7 is not compatible with previous versions of Rails. If you decide that it’s time to upgrade your applications to Rails 2.1, this article features some handy tips, while this other one warns you about a few gotchas.

Those of you who’re running a version of Ruby that shipped with Mac OS X should wait for the next Apple’s Software Update.

Ajax

Rails is opinionated software, but its support for plugins clearly demonstrates a certain openness to diverging opinions on non-core issues. So while most of us mainly use Protoype, it is fairly common to see folks adopting other JavaScript frameworks as well, particularly jQuery.

Last week Jim Neath published a nice overview which compares jQuery with Prototype, and provides information about using jQuery with Rails through the jRails plugin.

Whatever your Ajax framework of choice is, you may be interested in the new Google Ajax Library API to improve the performance of your applications. Thanks to the tutorial Using Google Ajax Libraries API with Ruby on Rails (soon to be incorporated into a plugin) you can start adopting the API with Rails right now.

MVC

Rails 2.1 adds named scopes, which greatly simplify writing “find logic” within your Active Record models. It’s an extremely useful feature which is well explained in this write-up aptly titled, Named Scopes Are Awesome (we agree). Checkout also Ryan Bates’ railscasts on the subject: named_scope and Anonymous Scopes. You may also be interested in this week’s railscast about Caching in Rails 2.1.

Three other compelling Active Record related posts were, Smart Model, Dumb Controller, Bulk insertion of data with ActiveRecord and Timestamped Migrations on how to make “classic migrations” an available option (see ticket).

Michael Bleigh published a tutorial about dealing with subdomains in Rails applications through the SubdomainFu plugin (which appears to be flexible and very straightforward to use).

XP programming practices such as Test-Driven Development are very popular within the Rails community, but there are still many developers who see testing as a chore. Josh Nichols wrote an overview called A walk through of test-driven development with shoulda that shows you how easy it is to apply TDD to your Rails projects. In this specific case, he adopted the Shoulda plugin which seamlessly adds some assertions, helpers and macros on top of the Test::Unit framework.

Documentation

Aside from api.rubyonrails.org there are many alternatives for quickly visualizing the documentation of the Rails’ API. Last week a new one was launched: rails-doc.org. The current version features rapid searches and user annotations. This last feature in particular has the potential to become truly useful.

Deployment

If you are using Apache and mod_rails, you may want to read this article which provides information about a newly released module called apache-upload-progress.

Finally, Jason Crystal wrote a tutorial for packaging Rails applications for offline use on Mac OS X 10.5.


We’re done for this week. If you’d like to read more updates from the Ruby side of things, please head over to This Week in Ruby.

Living on the Edge (or what's new in Edge Rails) #2 - Performance improvements

The first Living on the Edge covered some of the API changes since Rails 2.1, and this time round, I’m going to cover the performance improvements as promised.

Jumping right in…

Faster Erb templates

Jeremy Kemper has made the Erb processing more efficient, especially the concat and capture helper methods.

The “special” Erb _erbout has been replaced with an instance variable, which allows for:

  • better (memory) performance because bindings are no longer being passed around,
  • fewer evals which are usually expensive,
  • there’s no need to slice the _erbout variable when you can swap in a new (string) buffer, and
  • the buffer is actually available via a output_buffer reader and writer methods (so you can override it if you want).

Relevant changesets: 933697a
- 0bdb7d3
- 4d4c8e2

Faster partials and JavaScript helpers

Partial template initialization and JavaScript helpers have been refactored and optimized for speed and efficiency by Jeremy Kemper. These are but a few of the optimizations Jeremy has been committing recently. Be sure to check out some of the commits to Rails (or for that matter, any quality Open Source project) – you could learn something!

Relevant changesets: partialsJavaScript helpers

RecordIdentifier methods speedup

The RecordIdentifier has been sped up by some simple use of memo-ization, thus reducing the number of inflections performed, among other things. The RecordIdentifier is used widely in cache keys, partial template paths, and in most places where you identify an ActiveRecord model without caring about its actual id.

Relevant changesets by Jeremy Kemper: c1a9820566d717

Lazy load cache and session stores

Update: Oops my bad, this change was later reverted in 6573f6a.

The various cache stores in the ActiveSupport::Cache module are now lazy loaded – this means that they are only required when you actually start using them.

Changeset by Pratik Naik

Multiple Ruby security vulnerabilities

Drew Yao at Apple uncovered a handful of nasty security vulnerabilities affecting all current versions of Ruby. The details are still under wraps because an attacker can DoS you or possibly execute arbitrary code — holy crap! Better upgrade sooner than later.

According to the official Ruby security advisory, the vulnerable Rubies are:

  • 1.8.4 and earlier
  • 1.8.5-p230 and earlier
  • 1.8.6-p229 and earlier
  • 1.8.7-p21 and earlier

Those of us running Ruby 1.8.4 or earlier must upgrade to 1.8.5 or later for a fix. Those on 1.8.5-7 can grab the latest patchlevel release for a fix.

(Please note: Ruby 1.8.7 breaks backward compatibility and is only compatible with Rails 2.1 and later, so don’t go overboard!)

Living on the Edge (or what's new in Edge Rails) #1 - API changes and PerformanceTests

As Gregg Pollack mentioned a week or so ago, I’ll be keeping a weekly-or-so column about noteworthy changes on edge Rails. This is the first time Living on the Edge (of Rails) is appearing on the official Ruby on Rails weblog, so you’ll have to bear with my short introduction.

Living on the Edge is a weekly column I used to put up on my own blog after some prodding by Gregg Pollack of Rails Envy way back in December of 2007. I used to be a rather active Rails contributor back then so it was a no-brainer. Gregg and Jason were awesome enough to feature it weekly in their podcast.

And now it’s here, so try your best to be a tough crowd so I can tune these blog posts so that they are actually useful to you – when I was blogging these on my tiny personal blog it wasn’t that vital but now the audience is significantly larger. Leave your suggestions and criticisms in the comments – they are greatly appreciated!

Anyway, there’s been a ton of new features, API changes and performance improvements in the past 2 weeks or so since Rails 2.1 was released, so rather than dumping all into one mega-post, I’ve decided to break it into 2 posts for new features/API changes and performance improvements. In this post, I’m gonna talk about some of the new features and API changes.

Minor API changes

Let’s start jump straight in with some minor API changes.

link_to now takes a block

The link_to helper now takes a block argument for those occasions when you have really long hyperlink text with variables in them:

<% link_to(@profile) do %>
  <strong><%= @profile.name %></strong> -
  <span>Status: <%= @profile.status %></span>
<% end %>

Some people would find it cleaner than:

<%= link_to "<strong>#{@profile.name}</strong> -- <span>Status: #{@profile.status}</span>", @profile %>

Credit goes to Sam Stephenson (of Prototype fame) and DHH for this change.

Changeset details

ActiveRecord::Base#merge_conditions is now part of the public API

Jeremy Kemper has made ActiveRecord::Base#merge_conditions a public method.

This is pretty useful if you have conditions from multiple sources or like to combine any conditions for any reason.

Post.merge_conditions(
  {:title => 'Lucky ☆ Star'},
  ['rating IN (?)', 1..5]
)
=> "(`posts`.`title` = 'Lucky ☆ Star') AND (rating IN (1,2,3,4,5))"

Do note though that this merges with a SQL boolean AND only (no ORs).

Changeset details

Associations now take a :validate option

Association macros now accept a :validate option like so:

class Anime > ActiveRecord::Base
  has_many :characters, :validate => true
end

This tells ActiveRecord to validate the characters association when saving your Anime model – just like how :validates_associated works. The default is false, which is the current behavior in Rails 2.1 and earlier, so no need to fret. This works for all the other association macros as well (has_one, belongs_to, has_and_belongs_to_many).

Thumbs up to Jan De Poorter and Pratik Naik for this, which also fixes a nasty bug.

Changeset detailsTicket

ActiveSupport::StringInquirer and convenience Rails.env.development? methods

David Heinemeier Hansson (henceforth abbreviated as DHH – sorry!) recently added an ActiveSupport::StringInquirer String subclass that allows you to do this:

s = ActiveSupport::StringInquirer.new('awesome')
=> "awesome"
s.awesome?
=> true
s.sucks?
=> false

An immediate use of this is when you are checking the environment your app is running in: Rails.env is wrapped in a StringInquirer so you can use query methods like Rails.env.development? and Rails.env.production?.

Changeset details

Core extensions: Object#present? and Enumerable#many?

DHH also added some core extensions that while trivial, could make your code more readable. First up is Object#present?, which is essentially !Object#blank?

[].present?
=> false
[1, 2].present?
=> true
"".present?
=> false
"i'm here".present?
=> true

An Enumerable#many? extension was also added that is simply a boolean test for enumerable.size > 1:

[].many?
=> false
[:just_me].many?
=> false
[:just_me, 'my_friend'].many?
=> true

Object#present? changesetEnumerable#many? changeset

Declarative block syntax for writing tests

DHH was inspired by Jay Fields when he committed this bit of syntatic sugar: you can now write your tests (Test::Unit) in declarative block style like so:

test "an anime should be invalid if any of its characters are invalid" do
  # Your usual test code here.
end

I seldom use Test::Unit (except when submitting Rails patches) and prefer RSpec – this declarative style of writing tests is definitely more readable.

All Rails-generated test stubs now use this new syntax.

Changeset details

Performance tests

Jeremy Kemper has been hard at work optimizing and improving the performance of Rails, so it’s no surprise that he has also introduced a new type of integration test: the performance test.

You can use the performance test generator (added by Pratik in 23232a) to generate a performance test stub.

script/generate performance_test LoginStories

Running the performance test requires ruby-prof >= 0.6.1, which is still unreleased but you can get at it the development version by checking out the source and installing the gem yourself (I suggest you get Jeremy’s fork of ruby-prof for now). It’s interesting to note that with the 0.6.1 release, ruby-prof supports profiling tests cases written using Test::Unit.

Moving on… Put in some test code (request a few controller actions – whatever user story you want to test performance of) and run the test. You’ll get output like this (together with the usual ruby-prof profiling output in the test/tmp/performance directory of your Rails app):

> ruby performance/login_stories_test.rb 
Loaded suite performance/login_stories_test
Started
LoginStoriesTest#test_homepage (32 ms warmup)
        process_time: 11 ms
              memory: unsupported
             objects: unsupported
.
Finished in 0.870842 seconds.

The memory and objects results are “unsupported” because I haven’t patched my Ruby interpreter for memory profiling support. You’d need certain Ruby interpreter patches to enable memory and GC profiling. I wish I could tell you more about how to do so, but I’m treading unfamiliar ground here. There are some details here on how to patch Ruby for memory profiling. I leave it for wiser folks to explain how to do this :)

Changeset details

Outro

That’s it so far for new feature/API changes in Rails since Rails 2.1 – performance improvements are coming up in the next post and I’ve also intentionally left out mention of the Rack support that has been partially merged into edge.

If there were any errors or you have any suggestions on how to make this column better, please point them out in the comments. Any info on patching your Ruby interpreter for memory profiling support is also greatly welcome. If I’ve left out anything that I’d considered not noteworthy enough but you disagree, let me know in the comments too.

Ruby Conferences and Tracks

There are several Ruby / Rails related conferences coming up in the next few months. Some of these are smaller regional conferences, and some of them are larger conferences which have their own Ruby tracks. If you know of any additional events, please comment and I’ll add them to this list.

July 21-25 – OSCON in
Portland, Oregon

This year O’Reilly’s Open Source Convention is sporting a nice looking Ruby Track with several advanced topics. Yup, this is at the Portland Convention Center, same place as Railsconf.

Cost: $1345 (sessions only)

August 1-2 – Ruby Nation in
Herndon, VA

A Washington DC Regional area Ruby conference with a great location: right next to the Washington Dulles Airport.

Cost: $175

August 8-9 – Ruby Hoedown in
Huntsville, AL

A southeast regional Ruby conference located just down the street from the Space Center (aka Spacecamp).

Cost: $199

August 15-17 – erubycon in
Columbus, OH

A conference dedicated to Ruby’s place in the Enterprise, organized by EdgeCase.

Cost: $199

September 4-6 – Lone Star Ruby Conference in
Austin, TX

A regional Ruby conference deep in the heart of Texas. They haven’t announced their speakers or opened registration yet, but I’m told they will shortly.

Cost: $250

September 20 – Windy City Rails in Chicago, IL

A day long Rails conference in Chicago covering the freshest topics in the Rails world put together by Chicago Ruby.

Cost: $99

November 17-21 – QCon in
San Francisco, CA

InfoQ and Trifork (from JAOO) put together this annual San Francisco conference with a DSLs in Practice and Ruby for the Enterprise track that any Ruby programmer would probably enjoy.

Cost: $1,695 (sessions only)

Also worth mentioning:

  • Ruby Fringe is July 18-20, but tickets are no longer available.
  • Railsconf Europe is September 2-4 as David announced last week.
  • Rubyconf is November 6-8 in Orlando, FL, but rubyconf.org doesn’t have any information about that yet.
  • Voices that Matter: Professional Ruby Conference is November 17-20 in Boston, MA. I’m told more details will be revealed next month.
  • Merb Camp is hasn’t been officially announced yet, but I hear it might be October 11-12 in San Diego.
  • Railscamp #3 is going on this weekend (June 20-22) near Sydney, Australia, and there’s also a Railscamp UK being planned for sometime in August.
  • RuPy is this weekend (Saturday, June 21) in Omsk, Russia.

If I’ve missed any conferences, please let me know and I’ll be happy to add them.

This Week in Rails (June 16, 2008)

This is the first edition of This Week in Rails. As announced by Gregg Pollack a few days ago, this weekly column will cover highlights from the Rails community. My aim is to provide you with a status update as if you’d gone on holidays for a week. I will try to be consistent and publish once a week on Sunday or Monday. Being my first shot, I’ll rely on your feedback to verify that I’m on the right track and that this is useful to you; so please feel free to express your opinion in the comment section below.

With Rails 2.1 out, most developers are looking forward to upgrading their skills (and projects) to the latest release. If you’re one of them, I strongly recommend that you check out the second edition of Carlos Brando’s Ruby on Rails 2.1 – What’s new free e-book, which is available in both English and Portuguese, with an Italian translation currently in the works as well. You can also read Rob Anderton’s excellent overview of Rails 2.1’s improved caching capabilities, as well as its built-in support for memcached.

Last week, Phusion announced the first release candidate of Passenger 2.0 (aka mod_rails). This release introduces support for Rack, opening the door to alternative web frameworks as well. In the same announcement, Ruby Enterprise Edition was formally released. Despite the “Enterprise” label, this is a fully Open Source version of Ruby whose main claim is a reduced memory footprint on Linux and Mac OS X.

Speaking of Enterprise, Dr Nic has released version 1.0.2 of his Composite Primary Keys gem. Starting from version 1.0.0 it finally catches up with Active Record 2.1. Erubis, the fast alternative to ERB, has rolled out support for Rails 2.1 as well, in their 2.6.1 version. A week later, version 2.6.2 was released and it includes support for Ruby 1.9 as well. You can install it by running
gem install erubis or by downloading it from RubyForge.

Last week Ryan Bates put out another two Railscasts. The first is about how to contribute to Rails using Git and is, needless to say, highly recommended. The second one is in regards to substituting pagination with the effect of endless scrolling, like DZone does. As pointed out, there are plugins that do this, but Ryan’s approach builds it from scratch and is definitely worth checking out.

Other interesting articles were: a concise guide to using the Thinking Sphinx plugin (along with the pre-requisite Sphinx primer), Easy and Flexible Breadcrumbs for Rails even though they are clearly not everyone’s cup of tea, and lastly GemPlugins: A Brief Introduction to the Future of Rails Plugins.

In conclusion, two announcements were previously reported in this blog, but they are both worth repeating. The first is the release of Capistrano 2.4 and the second is that registration has opened up for RailsConf Europe 2008. The conference will be held in Berlin, Germany from the 2nd to the 4th of September. By registering before July 15th, you can save up to 150 euros.

That’s it for this week. As you can see there is no shortage of material, given that we’re such an active community. If you’d like to read more updates from the Ruby side of things, please head over to This Week in Ruby.

Capistrano 2.4.0

Capistrano 2.4.0 is now available. Capistrano is the deployment tool of choice for many Rails programmers, but can be used for much more, allowing you to automate remote tasks using a simple task-oriented framework in Ruby.

Install it via RubyGems:

  gem install capistrano

You can read the entire release announcement on Jamis Buck’s weblog.