The dilemma of Rails.root vs RAILS_ROOT complex

Since Rails 2.3.6, Rails Core Team’s recommended users to take advantage of Rails.root in preference to the old RAILS_ROOT instance variable. The good thing about Rails.root is that it returns a Pathname object so you could do something like this:

File.join(RAILS_ROOT, 'public')

to

Rails.root.join('public')

It definitely looks neater right? But the core team did not mention what convention for other cases such as

path = "#{RAILS_ROOT}/public"

should we convert it to:

path = Rails.root.join('public')

OR

path = "#{Rails.root}/public"

OR

path = Rails.root.to_s + "/public"

It is up to your own taste. IMHO, I prefer to use the "#{Rails.root}/public" to others. What do you think?

Updated: For path to public folder, the best way is to use

Rails.public_path

Hope this helps 🙂

About Jones Lee

Nothing much about me..

5 responses to “The dilemma of Rails.root vs RAILS_ROOT complex

  1. Robert

    I’ve found with Rails 3.0 rc that path = Rails.root + “/public” may not work. Instead I have to use path = Rails.root.to_s + “/public” or one of the other examples given in this article.

  2. As of Rails 3.0.7 RAILS_ROOT and RAILS_ENV are deprecated. Rails.root and Rails.env are preferred. Thanks for the post.

  3. To answer the OR question in your post, I think this is the most readable if you want the actual string:

    path = Rails.root.join(‘random’, ‘path’).to_s

  4. Nicklas Ansman-Giertz

    You should use File.join(Rails.root, ‘public’) instead to be cross platform

  5. Rails.public_path seem to be the better choice

Leave a reply to Robert Cancel reply