Ruby File Renaming Utility

I wrote a little renaming utility to help me with the all too common task of file re-naming that seems to keep coming up. The class itself is pretty general; the idea is to extend it and override the “valid_file” and “format” methods for whatever specific task I’m doing.

The “valid_file” method is intended to recognize which files need to be renamed in the case you’ve got files you don’t want to touch in the directory. By default the function just ignores the “.” and “..” in the directory listing.

The “format” method is used to to specify the actual rules and routine to use when renaming your file. By default it replaces spaces and dashes with underscores.

Finally, this isn’t “finished” software. No error checking, no notes. It works for me and maybe it’ll work for you too.

Here’s an example class I wrote using the renaming utility. It’ll prepend the string “prepend_” onto all png files in the specified directory. Note that there’s a “safe_mode” variable passed in the constructor. Setting the “safe_mode” to true will prevent the files from being renamed while you’re working on it.

require 'renamer'

safe_mode = false

class Example < Renamer

  def format file
    file = custom_format(super(file))
    puts file 
    return file
  end

  def valid_file file
    valid = super(file)
    valid = valid && file.include?('.png')
    return valid
  end

  def custom_format file
    return "prepend_#{file}"
  end
end

if __FILE__ == $0  
  path = ARGV[0]
  r = Example.new(path,safe_mode)
  r.rename_files
end

Download the code: Ruby File Renaming Utility