jueves, 6 de enero de 2011

generate Moose classes from CLI

It seems I've been a bit out of Perl lately (last 2 or 3 weeks), but that's not completely true.

I have a couple of projects in mind (one bigger than the other, but both interesting nonetheless), but I have not been in my best moods to program... difficulties to focus. At work, I do exactly 0% perl :(, so I have to push myself to use it...

In one of my projects I'm using OOP intensively (maybe overengineering?, we'll see), and I always tend to forget how to correctly set up a bare Moose class.

So here's what I've written:
#!/usr/bin/perl
# vim: set tabstop=4 shiftwidth=4 foldmethod=marker :
#{{{
=head1 NAME
genclass.pl - Generates templates for moose classes
=head1 SEE ALSO
Vim, emacs, or any decent editor with macros
=head1 SYNOPSIS
kidd@yoda [ /tmp/proj ] %genclass.pl lib/My/App/Module
#generates package My::App::Module
#TIP: use tab completion wisely :)
=head1 DESCRIPTION
Moose classes are really concise and expressive, and there's
very little boilerplate to write, but I keep forgetting
writting the right paths and so. A couple of attributes are
provided to show default and lazy attributes.
=head1 AUTHOR
Raimon Grau Cuscó <raimonster@gmail.com>
=head1 Credits
=cut#}}}
use Data::Dumper;
use Getopt::Long;
use Pod::Usage;
use File::Path qw(make_path);
use strict;
use warnings;
sub man {#{{{
pod2usage(
-exitval => 1,
-verbose => 2
);
}#}}}
my $path_and_classname=shift or die "must supply a path+classname";
die "file $path_and_classname already exists" if -f "$path_and_classname.pm";
$path_and_classname =~ m[^(.*)/(.*)] ;
my $class_path = $1;
my $class_name = $2;
make_path $1 and warn "Warning: directory $1 alredy exists. continuing";
open my $fh ,'>',"$path_and_classname.pm" or die "cannot create file. $!";
$path_and_classname =~ s|^lib/||;
$path_and_classname =~ s|/|::|g;
while ( <DATA> ) {
s/%%%/$path_and_classname/;
print $fh $_;
}
# main
GetOptions (
'man' => \&man,
);
__END__
package %%%;
use Moose;
use autobox;
use autobox::Core;
use Perl6::Say;
has 'one' => (is =>'ro', isa =>'Int' , default=> sub { 1 }});
has 'attr' => (is =>'rw', isa =>'Num' , lazy_build=>1);
sub _build_attr {
my $self = shift;
return $self->one+1;
}
no Moose;
__PACKAGE__->meta->make_immutable;
1; # End of %%%;
view raw genclass.pl hosted with ❤ by GitHub


Just a simple script that generates scaffolds for Moose classes and gives a couple of hints on attributes' properties. A good friend of the script template I did some time ago

I've tried to make it work the most DWIM-Y way, so you call it like "genclass.pl lib/My/App/Entity" , and generates My::App::Entity class in the appropiate path and with appropiate namespace.

SeeYapp! ;p

No hay comentarios: