Search code examples
ruby-on-railsrubyruby-on-rails-3rubygemsruby-on-rails-2

Support both Rails 2 and Rails 3 in gem


I'm wondering if there are any gems out there that support both Rails 2 and Rails 3? If so, how do they do it? Simple conditionals in the code?

This is related to my previous question: Packaging Rails 2.3 Models

Our webapp is on Rails 2, but the new API app is going to be Rails 3. There are already some minor incompatibilities between the two that would be easy to fix with a release script, or with runtime conditionals.

[edit] We do plan to eventually have both the API server and App server running on Rails 3, so this would be for the interim. My current thinking is that an if-def solution might be the simplest and easiest. (See: http://www.infoq.com/presentations/Simple-Made-Easy)


Solution

  • If you have some minor differences between Rails 2 and 3 (e.g. a renamed method) you should go fine with a few conditionals. Here is an example from Haml-rails

      if ::Rails.version.to_f >= 3.1
        config.app_generators.template_engine :haml
      else
        config.generators.template_engine :haml
      end
    

    If you have major differences you should keep two separate gems. For example, will_paginate has 2.3 version for Rails 2 and 3.0 one for Rails 3 because of a major refactoring in Active Record 3. Only 3rd version is under development.

    Record.find(:all, :conditions => { :foo => 'bar' }, :limit => 5) # Rails 2
    Record.where(:foo => 'bar').limit(5) # Rails 3
    

    In that case if you have to maintain two versions you may also want to consider 3 gems: mygem (core), mygem-rails2, mygem-rails3. The latter two will depend on the core and reuse the same rails-independent code.