Slashing File.join in Ruby
If you’re doing some file system manipulations in Ruby, moving and creating files around (which it does very well as it doesn’t try to ignore, like Java, that there is a file system) you have basically two choices: hard code a lot of ‘/’ characters in your code, which isn’t pretty, or use File.join. After a while you end up with many of these joins all over the place and it’s not so pretty (there’s actually a third possibility, you can directly use File::SEPARATOR, but it’s so ugly that I’m not counting it).
Yesterday, I had this really simple idea:
class String
def /(str_to_join)
File.join(self, str_to_join)
end
end
It’s so sweet and easy that I can’t even figure why I’ve never thought of it before. Now I can do:
'tmp'/'readme.txt' # literals
ROOT_DIR/file_path # variables holding strings
Much easier on the eyes and the fingers.
No comments yet
Leave a reply