Some little hacks and random thoughts on what interests me at the moment in the area of computer science.
Debugging Rails
There are many ways in which you can debug your Rails applications, I’m going to show you how to display the errors you get in a nice way, using Better Errors, and what to do when that just isn’t enough.
Better Errors
This was covered in great depth by Ryan Bates in a RailsCasts #402. After you install the gem, when you get an application error instead of this:
You’ll be prompted with something like this:
Note that by adding binding_of_caller gem you’ll also have a REPL on the point of failure.
Pry
Better errors with a REPL is going to take care of most of your problems when doing a full stack request, but if you are developing some model classes or even some libraries in Rails or plain old Ruby, you may want to declare breakpoints so you can do some debugging.
Debbuging with pry is as easy as droping the binding.pry line wherever you want the breakpoint, like so:
When running this code, your server will stop at the breakpoint and you should see this:
This has been covered on RailsCasts #280. One thing Ryan doesn’t mention though is the pry-rails gem, which will sub in as your rails console and give you some nicities as showing routes and the schema for a given model in a good looking way.
$railsconsole[1]pry(main)>show-routespokemonPOST/pokemon(.:format) pokemons#create new_pokemon GET /pokemon/new(.:format)pokemons#newedit_pokemonGET/pokemon/edit(.:format)pokemons#editGET/pokemon(.:format) pokemons#show PUT /pokemon(.:format)pokemons#updateDELETE/pokemon(.:format) pokemons#destroy beer POST /beer(.:format)beers#createnew_beerGET/beer/new(.:format)beers#newedit_beerGET/beer/edit(.:format)beers#editGET/beer(.:format) beers#show PUT /beer(.:format)beers#updateDELETE/beer(.:format) beers#destroy[2] pry(main)> show-routes --grep beer beer POST /beer(.:format)beers#createnew_beerGET/beer/new(.:format)beers#newedit_beerGET/beer/edit(.:format)beers#editGET/beer(.:format) beers#show PUT /beer(.:format)beers#updateDELETE/beer(.:format) beers#destroy[3] pry(main)> show-routes --grep new new_pokemon GET /pokemon/new(.:format)pokemons#newnew_beerGET/beer/new(.:format)beers#new[4]pry(main)>show-modelsBeerid:integername:stringtype:stringrating:integeribu:integerabv:integercreated_at:datetimeupdated_at:datetimebelongs_tohackerHackerid:integersocial_ability:integercreated_at:datetimeupdated_at:datetimehas_manypokemonshas_manybeersPokemonid:integername:stringcaught:binaryspecies:stringabilities:stringcreated_at:datetimeupdated_at:datetimebelongs_tohackerhas_manybeersthroughhacker$DISABLE_PRY_RAILS=1railsconsoleirb(main):001:0>