Documenting web services with Perl POD and AJAX
Perl POD is a handy, convenient, but low-tech approach to embedded documentation. Consider a web service in Dancer:
get time => sub {
return scalar(localtime());
};
(Disclaimer: my actual use-case of this technique was even more legacy: I was documenting Interchange Actionmaps that returned images, JSON, etc.)
Your application might have several, or even dozens of these, with various parameters, returning data in JSON or TXT or CSV or who-knows-what. I chose to document these in Perl POD (Plain Old Documentation) format, e.g.,
=pod
=head1 time
Retrieves the current time
=over 3
=item Parameters
None.
=item Example
=begin html
<script src="/js/example-time.js" type="text/javascript"></script>
=end html
=back
=cut
This block gets inserted right in-line with the web service code, so it’s immediately obvious to anyone maintaining it (and thus has the best chance of being maintained if and when the code changes!). Now I can generate an HTML page directly from my Perl code:
$ pod2html MyPackage.pm
Your output looks something like this (excerpted for clarity):
time
Retrieves the current time Parameters
None.
Where the magic comes in is the JavaScript code that allows an in-line example, live and accurate, within the documentation page. You’ll actually get something more like this:
time
Retrieves the current time Parameters
None.
(results appear here)
Note that the code I have below is not factored by choice; I could move a lot of it out to a common routine, but for clarity I’m leaving it all in-line. I am breaking up the script into a few chunks for discussion, but you can and should construct it all into one file (in my example, “js/example-time.js”).
/* example-time.js */
$(document).ready(
function(){
$('script[src$="/example-time.js"]').after(
"<form action='\"/time\"'>" +
/* Note 1 */
"<input data\"="" type='\"submit\"' value='\"Get'/>" +
"<input name="hide" none\"="" result\"="" style='\"display:' type='\"button\"' value='\"Hide'/>" +
"</form>" +
"<div id='\"time-result\"'></div>"
);
Note 1: This being a painfully simple example of a web service, there are no additional inputs. If you have some, you would add them to the HTML being assembled into the