Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How long should "rake routes" run?

I just started out with Rails, so excuse my fairly basic question. I am already noticing that the rake routes command takes a while to execute everytime I run it. I have about 20 routes for 3 controllers and it takes about 40 seconds to execute.

Is that normal? How could I speed this up?

P.S.: I am on Windows 7 with Rails 3.1.3 (set up with Rails Installer).

like image 830
matt_jay Avatar asked Jan 21 '12 14:01

matt_jay


2 Answers

The rake routes task depends on the environment task which loads your Rails environment and requires thousands of Ruby files.

The startup time of a Rails environment and the corresponding rake routes execution time are very close (on my Linux on-steroids-laptop with a Rails application with ~ 50 routes):

$ time ruby -r./config/environment.rb -e ''

real    0m5.065s
user    0m4.552s
sys 0m0.456s

$ time rake routes

real    0m4.955s
user    0m4.580s
sys 0m0.344s

There is no easy way to decrease startup time as it relies on the way your interpreter requires script files : http://rhnh.net/2011/05/28/speeding-up-rails-startup-time

like image 196
Jef Avatar answered Oct 05 '22 23:10

Jef


I came up with a solution to rake routes taking about 8 seconds to run every time. It's a simple file based cache that runs bundle exec rake routes, stores the output in a file under tmp. The filename is the md5 hash of config/routes.rb, so if you make a change and change it back, it will use the old cached file.

I put the following bash functions in an executable file I call fastroutes:

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 {
  bundle exec rake 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
else
  main
fi

Here's a github link too.

This way, you only have to generate the routes once, and then fastroutes will used the cached values.

like image 40
tlehman Avatar answered Oct 05 '22 22:10

tlehman