miércoles, 25 de agosto de 2010

Using AUTOLOAD to build html code

Last week I found a new blog about Io. It's been a long time since I used Io, but maybe this blog will make me look at Io Language again.


In his last post, Dennis Ferron comments on _why's web server yown written in Io. One thing he comments is the slot 'forward'.

As he says, forward is a kind of catch that gets called when a message has been sent to an object and that object didn't have a selector with that name. _why exploits this feature to write an html builder based on that.

What he doesn't mention (I think he's leaving this for another post) is about lazyness. The way _why wrote forward method.

If you define a method without arguments but you call it with some, you can still access them, but with the difference that they won't be evaluated by default. That's called lazyness, and allows you to define the evaluation order of things.

So in the code

html(
title("O HAI")
strong("KTHXBYE")
)


forward will trap html message before title or strong.

In Perl, there's a 'lightning rod' function too, called AUTOLOAD. You can do pretty much the same, but the difference is that perl will ALWAYS evaluate parameters sent to a function before calling it, so the same code would trigger AUTOLOAD on the 'title' call, then 'strong', and last, 'html' and you have to fill the string from the inner tag to the most generic one.

Here's a gist code that emulates Yown Builder.io in Perl 5.

#!/usr/bin/perl
use Data::Dumper::Perltidy;
use Getopt::Long;
use Perl6::Say;
use Pod::Usage;
use autodie;
use strict;
use warnings;
our $AUTOLOAD;
sub man {#{{{
pod2usage(
-exitval => 1,
-verbose => 2
);
}#}}}
# main
GetOptions (
'man' => \&man,
);
sub AUTOLOAD {
$AUTOLOAD=~ /.*::(.*)$/;
my $fill='';
my @a = split(/_/,$1);
if (1<@a) {
$fill=" class='$a[1]'";
}
return "<$a[0]$fill>\n@_\n</$a[0]>\n";
}
say hola(
adeu_thisismyclass("hola"),
ital()
);
__END__#{{{
=head1 NAME
AutoBuild
=head1 SEE ALSO
=head1 SYNOPSIS
say hola(
adeu_thisismyclass("hola"),
ital()
)
outputs
<hola >
<adeu class='thisismyclass'>
hola
</adeu>
<ital >
</ital>
</hola>
=head1 DESCRIPTION
Tiny DSL to dinamically build html-like text based on AUTOLOAD Perl5 feature
=head1 AUTHOR
Raimon Grau Cuscó <raimonster@gmail.com>
=head1 Credits
=cut
# vim: set tabstop=4 shiftwidth=4 foldmethod=marker : ###}}}
view raw AutoBuild.pl hosted with ❤ by GitHub



Good luck Dennis with your new blog!

--
raig

No hay comentarios: