Wednesday, March 22, 2006

Ruby noob

Caution: this is a computer-related posting, so skip it if you are not interested. It's a neat trick I learned a while ago, and it's served me well. I'm sure it can be improved in many ways, but at least it has helped me learn a bit of Ruby.

Problem: I usually keep my office PC and my Mac laptop synchronized using rsync. I do something like

rsync -e ssh -auvz <office>:<dir> <dir>

when the most recent changes are on the office PC, and

rsync -e ssh -auvz --exclude=".DS_Store" <dir> <office>:<dir>

when I finish working on the laptop and want to sync up everything ot my office PC. The additional "exclude" is necessary to avoid copying files created by the OSX Finder in practically every directory, and for which Linux obviously has no use.

Anyway, the other day I forgot this "exclude" thingy, and as a result my office PC was littered with .DS_Store files all over my working directories. How to get rid of them (short of hunting them down manually)?

I knew about Python's os.walk, but could something like that be done in Ruby, which for some reason I find more compatible with my way of thinking? YES! Here goes:

require 'find'
require 'FileUtils'

Find.find("top_level_working_directory") do |path|
FileUtils.rm(path, :verbose => true) if path[-9..-1]==".DS_Store"
end


This thing recurses through all subdirectories, starting with top_level_working_directory and passes each file to the block, which then performs the required deletion if the (full) path matches the loathed pattern.

I am sure there are other ways, including turning this into a one-liner (I still launched irb and did things by trial and error), but this Worked for Me (TM).

0 Comments:

Post a Comment

<< Home