Sep 21

Mason finally has a tidier: masontidy. It runs perltidy on the various sections of Perl code embedded in Mason components. It works on both Mason 1 and Mason 2 syntax.

One nice trick is that it indents %-lines relative to each other, regardless of intervening content. e.g.

    % foreach my $article (@articles) {
    %     my $title = $article->title;
    <% $title %>
    %     if ( $article->has_related_links ) {
    %         foreach my $link ( $article->related_links ) {

Given my devotion to code tidying in general, this ought to have been written a long time ago, but the perfect became the enemy of the good. I always imagined a tidier that would reformat the HTML content simultaneously, so that for example the <li> would be indented inside the <ul> above.

This turns out to be difficult and fraught with edge cases. What if an HTML tag is generated inside Perl code and can’t be seen by the tidier? What about embedded javascript and CSS? Every time I encountered these problems I’d shelve the project.

In the end I decided half a solution is better than none. The current masontidy doesn’t attempt to tidy the HTML or non-Perl content. Perhaps someday I’ll figure out how to do it, but the current tool is still a big improvement.

Leave a Reply

preload preload preload