'Correct way to test Rails version for gem authoring

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


Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alex D
Solution 3 akostadinov