Search code examples
ruby-on-railsrubyglob

Why does Dir.glob return an empty array in a Rails app template?


I am implementing a custom Rails app template with a .remove file that lists glob-style patterns of files (e.g. app/**/*.erb) to be removed after bundle install finishes:

removals = File.readlines('/path/to/.remove')
cwd = Dir.getwd

after_bundle do
  # Process removals
  removals.each do |pattern|

    puts 'glob:'+cwd+'/'+pattern           # glob:/Users/acobster/starfruit/app/**/*.erb
    puts Dir.glob(cwd+'/'+pattern).count   # 0
    puts `tree #{cwd}/app`                 # all files in the app tree, 
                                           # including several .erb files

    Dir.glob(cwd+'/'+pattern).each do |filepath|
      puts "        removing #{filepath}"
      remove_file(filepath)
    end
  end
end

According to the debug code (see comments above), the files I want to delete (in this case all .erb files under the app/ tree) are there in the tree, but the equivalent of Dir.glob('/Users/acobster/starfruit/app/**/*.erb') is returning an empty array.

Weirder yet, when I run Dir.glob('/Users/acobster/starfruit/app/**/*.erb') from irb, it correctly returns the array with the three .erb files present.

What's going on?


Solution

  • Turns out I was just forgetting to strip off newlines from the glob patterns. I changed the first line to

    removals = File.readlines('/path/to/.remove').map(&:strip).reject(&:empty?)