Rubyize This: Live in Vancouver. Refactoring #3

published Jan 27, 2008

Here’s the final refactoring from the Rubyize This workshop. See the first refactoring for an explanation of what’s going on and why this code is so darn ugly! The second refactoring is worth checking out as well.

#!/usr/bin/env ruby

def delete_large_files(directory, max_size)
  
  # Make sure directory ends in a slash
  if directory !~ /\/$/
    directory += '/'
  end
  
  # Find all of the files in the directory 
  files = Dir.glob(directory + '*')
  
  # Delete all files with size larger than max_size
  for file in files
    size = File.size(file)
    if size >= max_size
      File.delete(file)
    end
  end
  
end

max_size = 1024 * 50 # 50 kb
directory = './files_to_delete'
delete_large_files(directory, max_size)

This was the final refactoring, and the end of the conference, so we sort of ran out of time.

I didn’t get a change to show off my solution. Here it is.

def delete_large_files(dir, max_size)

  files_to_delete = Dir.glob(File.join(dir, '*')).select do |file|
    File.size(file) > max_size
  end

  File.delete(*files_to_delete)

end

What’s going on with that File.delete call?

First, File.delete takes multiple arguments and deletes all of them.

Second, I used the asterisk operator. From here:

“The asterisk operator may also precede an Array argument in a method call. In this case the Array will be expanded and the values passed in as if they were separated by commas.”

I don’t think I’ve every actually used the asterisk operator in production code, but it sure came in handy here.

blog comments powered by Disqus