9

What is the correct way to manage conditional flow in a gem based on Rails version?

Rails 4 changes some things so I need to conditionally flow based on Rails major version being 4 vs. 3 or prior.

The closest I've come is:

if Rails.version.split(".").first.to_i < 4
    # Do the Rails 4 thing
else 
    # Do it the old way
end
6
  • Don't you specify your Rails version in your Gemfile?
    – Nobita
    Jul 2, 2013 at 19:07
  • I'm authoring a gem and it needs to support Rails from version 2.x to 4.x. Unfortunately, Rails 4 changed one of the core ActiveSupport components (factored out to a gem of its own, actually), so I need to change behavior of the gem for Rails 4 (it still works fine for versions 2.x - 3.x). Jul 2, 2013 at 19:15
  • I am not sure if you will be able to do that..My thinking is that once your gem is built, Rubygems will run that code and create a static representation of it...
    – Nobita
    Jul 2, 2013 at 19:31
  • The above works I just don't think its the Rails Way to do it. All I need to do is check at run/load time what the Rails version is so that the gem continues to support each version of Rails appropriately. Jul 2, 2013 at 19:35
  • "4.0.1".to_i is 4. You don't need to split if you don't care about anything after the decimal place.
    – tadman
    Jul 2, 2013 at 19:57

3 Answers 3

20

Rails defines constants under Rails::VERSION for the various patch levels: MAJOR, MINOR, TINY and PRE (if applicable). The version string is constructed from these integers, and you can use them directly:

if Rails::VERSION::MAJOR >= 4
  # Do the new thing
else
  # Do it the old way
end

These go back to at least Rails 2.0.x so they should be safe to use for your gem's permitted dependency spec.

0

Personally, I think Rails.version =~ /^4/ reads much better.

1
  • Rails.version.to_i >= 4 is also an alternative.
    – tadman
    Jul 2, 2013 at 19:58
0

Safest simple way is to use for example

Gem::Version.new(Rails.version) >= Gem::Version.new('5.1')

Unless you really need to only compare the major version.

Credits to https://stackoverflow.com/a/3064161/520567

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.