I Rails how is template compilation implemented and optimised?
I Rails how is template compilation implemented and optimised?
To understand how template compilation is implemented and optimized in Rails, we can look at a few key files and concepts:
Searched for 'ActionView::Template' in rails/rails
Based on the search results, here are the key points about how template compilation is implemented and optimized in Rails:
Templates are compiled by handler classes under ActionView::Template::Handlers
. The file extension of the template determines which handler is used (e.g. ERB, Raw).
Template handlers convert the template code into Ruby code. For example, ActionView::Template::Handlers::ERB
compiles ERB templates.
The compiled Ruby template code is evaluated in the context of an ActionView::Template
instance to render the final output.
Templates can specify which locals (variables) they expect using a special comment syntax like <%# locals: (foo, bar) %>
. This allows for strict local variable checking and better error messages when expected locals are missing.
Template compilation is optimized by caching the compiled template code. ActionView::Resolver
is responsible for resolving template paths and handles caching.
In development mode, template caching is typically disabled so changes are picked up without restarting the server. The cache_template_loading
config controls this.
Some micro-optimizations are applied during template compilation. For example, the ERB handler uses a faster Erubi
implementation by default.
Raising ActionView::Template::Error
exceptions allow template errors to be handled specifically by the framework, providing better error pages and logging.
So in summary, Rails compiles templates into cached Ruby code via handlers matched to the template format. This compiled code is evaluated in the context of the template to render the final HTML, optimizing for performance while still allowing rapid development iterations.