Making rails routes FAST!

I work in a lot of Rails projects and one of my pet peeves is how long it takes to boot up Rails if all you need to do is view the generated routes with rails routes.

A long while back I found/copied/modified this bash function from tlehman, on GitHub.

What does it do? It stores the routes in a text file when you run the command. The file is named with an md5 checksum based on the contents of the routes file. If the file changes, the function will regenerate the routes. You can also force it to regenerate the file with the -r option.

I'm no bash expert, so I'm sure there's a better way of doing this, but it works for me.

function fast-rails-routes() {
	if [ ! -f config/routes.rb ]; then
		echo "Not in root of Rails app"
		exit 1
	fi

	cached_routes_filename="tmp/cached_routes_$(md5 -q config/routes.rb).txt"

	function cache_routes {
		echo "Generating new cache..."
		rails routes >$cached_routes_filename
	}

	function clear_cache {
		for old_file in $(ls tmp/cache_routes*.txt); do
			rm $old_file
		done
	}

	function show_cache {
		cat $cached_routes_filename
	}

	function show_current_filename {
		echo $cached_routes_filename
	}

	function main {
		if [ ! -f $cached_routes_filename ]; then
			cache_routes
		fi

		show_cache
	}

	if [[ "$1" == "-f" ]]; then
		show_current_filename
	elif [[ "$1" == "-r" ]]; then
		rm $cached_routes_filename
		cache_routes
		show_cache
	elif [[ "$1" == "-h" ]]; then
		echo "Print all routes"
		echo "$ fast_rails_routes"
		echo
		echo "Clear the cache and print all routes"
		echo "$ fast_rails_routes -r"
		echo
		echo "Print out the cache file name"
		echo "$ fast_rails_routes -f"
	else
		main
	fi
}