Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 540
Michael Lang Avatar asked Jul 02 '13 18:07

Michael Lang


1 Answers

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.

like image 119
SimonC Avatar answered Oct 31 '22 03:10

SimonC