perlmoose

Is this a correct (intended) usage of MooseX::Getopt?


Is this a correct (intended) use of MooseX::Getopt? The documentation doesn't have a lot of examples. The code works, but I don't know if this was the intended usage model.

package AppOpt {
    use Moose;
    use Moose::Util::TypeConstraints;
    use namespace::autoclean;

    with 'MooseX::Getopt';

    enum 'ReportType', [qw( activityByEvent activityByDate final )];
    enum 'FormatType', [qw( text pretty html )];

    has report => ( is => 'ro', isa => 'Str', required => 1 );

    has verbose => ( is => 'ro', isa => 'Bool', default => 0 );

    has format => ( is => 'ro', isa => 'Str', default => "text" );

    __PACKAGE__->meta->make_immutable;
}

package main;
use strict;
use warnings;

my $opt = AppOpt->new_with_options();

printf("original \@ARGV = [%s]\n\n", join(' ', @ARGV));

# Please ignore this tasteless inspection of the object guts. -E
for my $k (keys(%{$opt})) {
    unless($k =~ /(usage|ARGV|extra_argv)/) {
    printf("%s => %s\n", $k, $$opt{$k});
    }
}
exit(0);

Specifically: Are the options intended to be their own Class? I can't be sure from the docs.

Also, would it be appropriate to use BUILD to further validate the options?

This may sound like more than one question, but I don't mean it to be. I've run with other modules before only to find that I misunderstood how they were intended to be used.


Solution

  • The role MooseX::Getopt sets up command line options for attributes (except for those starting with _) of the class it is used with (consumed by). It is not intended to be "used" on its own.

    So you write a class AppOpt, with attribute report, and when you include MooseX::Getopt role you can call the program with --report..., where option details are set by inferring as much as possible about the attribute from its class. That's it. You get command-line options.

    A few accessors are provided, that one can use to inspect what happened on the command line, listed in your regex. But use them as accessors (methods), not by directly poking at the object.