Boldr by N. Merouze

How to upgrade plugins to Rails 3.0

Rails 3.0 beta is out and it’s now time to upgrade all the plugins available. To show you how to do it I’ve decided to create a small plugin compatible with Rails 2.x and Rails 3.0. It’s a wrapper around Rack::Cache to insert it automatically in a Rails application.

It’s a gem

First things first we create the gem we will name rails-cache. Thanks to Jeweler it’s dead easy. Just a few lines of code in a Rakefile and it’s done:

To create the VERSION file a echo "1.0.0" > VERSION is enough.

Rails 2.x way

The code of the gem will be in lib/rails/cache.rb and it’s just the insertion of the Rack::Cache middleware:

We build the gem with rake build and we install it with gem install --local pkg/rails-cache-1.0.0.gem. Then we need to load it in our environment.rb:

Rack::Cache is now plugged with the Rails application!

The new way

Rails 3.0 comes with Bundler. A cool thing with Bundler is that you can load a gem which have a custom path:

The :path option is the path to our gem. We have a lot of solution to do the same in Rails 2.x, with a plugin instead of a gem for example, but it is not as elegant as with Bundler (Bundler is usable with Rails 2.x).

To create a plugin for Rails there’s an object for that now, Rails::Railtie. So we just need to write an object which inherit from Rails::Railtie in lib/rails/cache.rb:

The gem has been upgraded to Rails 3.0!

Rails 2.x and 3.0 in a gem

This is just an example here, but it’s possible there’s a better solution:

And you can find the whole code on GitHub.

More about Plugins/Engines