Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some tips for debugging Ruby erb files?

Currently, when I get an error on an erb template (for use with HTTPServer/cgi) I do the following:

  • If it's a small change, revert, save and retest.
  • For a large change or new file, delete or comment 1/2 the code, and retest. Perform a binary search until I've deleted/found the broken code.

The call stack doesn't seem to correspond to anything in my .rhtml file.

(erb):6:in `block in <main>'
/opt/local/lib/ruby/1.9.1/erb.rb:753:in `eval'
/opt/local/lib/ruby/1.9.1/erb.rb:753:in `result'
bin/correct.rb:45:in `block in <main>'
/opt/local/lib/ruby/1.9.1/webrick/httpservlet/prochandler.rb:26:in `call'
like image 802
brianegge Avatar asked Aug 29 '09 05:08

brianegge


2 Answers

Not sure if this is applicable to this problem but maybe it will help someone. I'm using rails 5 and if you put

    <% debugger %>

in your html.erb file it will pause the terminal window that your rails server is running in. From there you can debug whatever params or variables your html.erb file has.

like image 109
Peter Tascio Avatar answered Sep 30 '22 15:09

Peter Tascio


As Daniel said, most times the error message will help you to quickly find where the error is.

There are indeed some occasions on which it doesn't.

The dumber, faster way to do that binary search is to just insert a wrong line, like

<%= the_error_is_after_this_line %>

and then move the line until you find the exact row.

I'm not one of those bright programmers who can write tons of lines per time which just work; i usually develop by small steps and reload the page on browser each time.

That said, the better way to avoid hard to debug views (or methods, or whatever) is to write simple, short ones. My rule of thumb is that I must be able to read the whole view (or method) in the editor window, unless it's just plain html.

Always use helpers and partial views. Can you count more than two () or [] in a line of your erb view? If yes, use a helper.

Can you count more than two or three blocks in your view? Use some partials.

like image 23
giorgian Avatar answered Sep 30 '22 15:09

giorgian