简体   繁体   中英

Rails.root with Dir

I seem to see a lot of people using Rails.root with Dir[]

Example: Dir[Rails.root.join('app', '*')

However, this seems unnecessary because functionally, it looks like Dir['app/*] does the exact same thing (and I personally prefer Dir['app/*'] over Dir[Rails.root.join('app', '*'] ).

I'm wondering is there any reason to use Rails.root with Dir or is it ok to not use Rails.root ?

Thanks!!

Anytime Dir.chdir is called (which could happen without you realizing it), it changes the assumed root. When Rails.root is used with Dir , the response stays consistent (which is what you want). However, when 'app' is used, the response is inconsistent, which will cause issues in your code.

You can play around with by copy / pasting the below text:

# copy / paste this into your rails console and view the results
def test
  puts 'start:'
  puts Dir[Rails.root.join('app')]
  puts Dir['app']
  Dir.chdir('app') do 
    puts nil
    puts 'note that Rails.root does not change but app does:'
    puts Dir[Rails.root.join('app')]
    puts Dir['app']
  end
  puts nil
  puts 'back:'
  puts Dir[Rails.root.join('app')]
  puts Dir['app']
end
test

More info can be found here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM