Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to glob a directory in Ruby but exclude certain directories?

Tags:

bash

shell

ruby

I want to glob a directory to post-process header files. Yet I want to exclude some directories in the project. Right now the default way is...

Dir["**/*.h"].each { |header|     puts header } 

Seems inefficient to check each header entry manually if it's in an excluded directory.

like image 956
jarjar Avatar asked Dec 22 '10 01:12

jarjar


People also ask

How do you exclude a directory in LS?

without directories — and here it is. Adding -ls or -exec ls -l {} \; would make it like ls -l without directories. find .

What is glob Ruby?

glob) in Ruby allows you to select just the files you want, such as all the XML files, in a given directory.

How do I change directory in Ruby?

chdir : To change the current working directory, chdir method is used. In this method, you can simply pass the path to the directory where you want to move. The string parameter used in the chdir method is the absolute or relative path.

What is directory in Ruby?

A directory is a location where files can be stored. For Ruby, the Dir class and the FileUtils module manages directories and the File class handles the files. Double dot (..) refers to the parent directory for directories and single dot(.) refers to the directory itself.


2 Answers

I know this is 4 years late but for anybody else that might run across this question you can exclude from Dir the same way you would exclude from Bash wildcards:

Dir["lib/{[!errors/]**/*,*}.rb"] 

Which will exclude any folder that starts with "errors" you could even omit the / and turn it into a wildcard of sorts too if you want.

like image 166
Jordon Bedwell Avatar answered Sep 19 '22 11:09

Jordon Bedwell


Don't use globbing, instead use Find. Find is designed to give you access to the directories and files as they're encountered, and you programmatically decide when to bail out of a directory and go to the next. See the example on the doc page.

If you want to continue using globbing this will give you a starting place. You can put multiple tests in reject or'd together:

Dir['**/*.h'].reject{ |f| f['/path/to/skip'] || f[%r{^/another/path/to/skip}] }.each do |filename|   puts filename end 

You can use either fixed-strings or regex in the tests.

like image 32
the Tin Man Avatar answered Sep 19 '22 11:09

the Tin Man