Rubyists, don’t forget about the dir glob!

If you are writing configuration to take a pattern to match against files in a file system…

You probably want Dir.globs, not regexes.  Dir.glob is in the stdlib. Dir.glob’s unix-shell-style patterns are less expressive than regexes, but probably expressive enough for anything you need in this use case, and much simpler to deal with for common patterns in this use case.

Dir.glob(“root/path/**/*.rb”)

vs.

%r{\Aroot/path/.*\.rb\Z}

Or

Dir.glob(“root/path/*.rb”)

vs.

…I don’t even feel like thinking about how to express as a regexp that you don’t want child directories, but only directly there.

Dir.glob will find matches from within a directory on local file system — but if you have a certain filepath in a string you want to test for a match against a dirglob, you can easily do that too with Pathname.fnmatch, which does not even require the string to exist in the local file system but can still check it for a match against a dirglob.

Some more info and examples from Shane da Silva, who points out some annoying inconsistent gotchas to be aware of.

This entry was posted in General. Bookmark the permalink.

One Response to Rubyists, don’t forget about the dir glob!

  1. Pingback: Non-digested asset names in Rails 4: Your Options | Bibliographic Wilderness

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s