One of my favorite things to do with Ruby is to write a quick throw away script to automate some mechanical changes to my code that can't easily be done with a text editor. Unlike normal code, the code can be downright bad and it's perfectly fine, because once the script runs, we can just delete it.

When dealing with a couple of resources, this isn't really a big deal. But when you have 10, 20, or more resources, doing all that by hand is slow. Sometimes we can accomplish these changes with a text editor, but since we'll have a bunch of path helpers that will all be different (and we'll also be moving files), there will still be a good chunk of manual editing. Luckily, we can write a throwaway script to do it for us!

We know that our changes are primarily breaking controllers and views. Let's start with views. We want to recursively loop through each view namespaced under foo. For this, we'll use Dir.glob. We'll glob our directories, check to make sure the current file in the iteration isn't a directory, and then find & change our path helpers.

Here we read the file, find anything that matches the format of a path helper that had the foo namespace, gsub it with the first and second captures, and append 'path' to it. Then, we write the file back. Notice, I included the code I used to test the regex when I ran the script, which logged it to the console instead of actually changing anything. I don't want to make any changes until I'm sure I have it right. This applies to any step here.

We also we want to move the file. The current path is the current item in the iteration, file. We can simply gsub out 'foo/' to get the path we want.

WOW that is some ugly code! The future reader of this code would have to stare at it for a minute or two before getting a handle on what's going on. But here, ugly code is the right tool for the job, because it can be written quickly, and once this script runs, we'll never need to run this again, so we can just delete it. I think this is much easier than doing it by hand (assuming you have a lot of files), plus, the more you write these types of scripts, the quicker you can write them in the future.

For the controllers, you could literally copy and paste (remember, we're deleting this!) the same chunk of code, replace views with controllers, and add a gsub for removing the "Foo::" namespacing.