A Sea of Views

Ruby on Rails projects tend to generate a large number of view files. In a recent, fairly-young project I found we had nearly 300 different files under app/views. On an older project we had over 1,400. These files are often intertwined, sometimes in non-obvious ways. When it comes time to make a change to such an application’s front-end, it can be difficult to locate exactly what file generated the markup seen in the browser.

Sign-Posts

To alleviate this pain, I wrote a simple wrapper around ActionView::PartialRenderer#render that bracketed the method’s output with html comments indicating which file had been rendered.

<!-- begin: app/views/user/_bio.html.haml -->
<div class='bio'>Ed's Bio</div>
<!-- end: app/views/user/_bio.html.haml -->

Adding Context

After throwing the code up on github, hinrik pointed out that knowing the file containing the markup in question was only half of the equation. Often the difficulty in working with nested view files is knowing where a view was called from. At his request, I extended my wrapper to indicate the view’s inclusion point.

<!-- begin: app/views/user/_bio.html.haml  (from app/views/user/show.html.haml:4) -->
<div class='bio'>Ed's Bio</div>
<!-- end: app/views/user/_bio.html.haml  (from app/views/user/show.html.haml:4) -->

Who This Helps

This was originally written to help me get a quick overview of the views structure of an existing project. I created the code as a gem and added it to the :development group. It turned out to be useful for the other developers on the team, but the real winners were designers. The designers who worked on this project also worked on several other projects simultaneously, not all Ruby on Rails. This tool enabled them to zero-in on the spots they needed to adjust without having to have a complete mental map of the project’s view structure.

The Code

rails_view_annotator has been published as a gem, and its source is hosted on github. Installation is as simple as adding gem 'rails_view_annotator' to a project’s Gemfile.

It has also been listed on under Rails Instrumentation.

Leave a Comment

Enclose code in <code lang="ruby"></code> if you care.
Preview your comment using the button below.