开发者

In Ruby, how can I inspect the class generated by a .html.erb template?

开发者 https://www.devze.com 2023-02-23 07:32 出处:网络
When doing J2EE development, I find it handy for debugging to view the Java classes that are generated by the JSP compiler.

When doing J2EE development, I find it handy for debugging to view the Java classes that are generated by the JSP compiler.

How can I do the equivalent in Ruby? Since it is all in memory, it won't generate a file that I can view. I believe it's the ERB module that generates the corresponding object for a template, so how can I actually view the object? Can I开发者_C百科 drop a debugger statement somewhere and use rdb? Is there some configuration value I can tell it to dump the object definition? I'm using rails, in case that makes a difference.


I don't think rails generates a class for your view. It basically calls eval after processing the file. Or do you mean inspecting the erb object while it's parsing your template?

If it's the latter you can find erb.rb in lib\ruby\1.9.1 I'd imagine you could just drop a debugger statement throughout that file.


I always make a habit of adding the following to my views (layout) which allows me to inspect or debug the parameters being used by the view in question.

<%= debug(params) %>

This will format all the parameters in yaml and display them in a Hash format.

Have a look at the method in the source code to get a better understanding. SOURCE


There are some differences compared with the Java way due to language differences.

Most template libraries for Ruby follow these steps when compiling/optimizing:

  1. The template is compiled into Ruby source code -- not a class but a long procedure that appends to a string buffer while traversing the logic of the original template.
  2. This ruby code is evaluated in order to be bound for later reference, preferably within a method body. This way, it is only parsed once by the interpreter.
  3. The method (or other context) containing the logic of the parsed template is invoked to render it.

Anyway, the compiled template code therefore looks a lot like a much noisier version of your original template, and will generally not help you debugging, unless you're debugging the template language itself.

Anyone interested in template language implementation might enjoy a look around the Tilt code (use different template languages with the same rendering interface and optimization), and Temple (a great template language meta-implementation).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号