Properly pull apart into roles
[gitmo/MooseX-Getopt.git] / lib / MooseX / Getopt / GLD.pm
CommitLineData
ef47fe44 1
33edcaa4 2package MooseX::Getopt::GLD;
ef47fe44 3use Moose::Role;
4
33edcaa4 5use Getopt::Long::Descriptive;
ef47fe44 6
33edcaa4 7with 'MooseX::Getopt::Basic';
ef47fe44 8
33edcaa4 9around _getopt_spec => sub {
10 shift;
11 shift->_gld_spec(@_);
ef47fe44 12};
13
33edcaa4 14around _getopt_get_options => sub {
15 shift;
16 my ($class, $params, $opt_spec) = @_;
17 return Getopt::Long::Descriptive::describe_options($class->_usage_format(%$params), @$opt_spec);
18};
a2099669 19
20sub _gld_spec {
21 my ( $class, %params ) = @_;
22
23 my ( @options, %name_to_init_arg );
24
25 my $constructor_params = $params{params};
26
27 foreach my $opt ( @{ $params{options} } ) {
28 push @options, [
29 $opt->{opt_string},
30 $opt->{doc} || ' ', # FIXME new GLD shouldn't need this hack
31 {
32 ( ( $opt->{required} && !exists($constructor_params->{$opt->{init_arg}}) ) ? (required => $opt->{required}) : () ),
33 # NOTE:
34 # remove this 'feature' because it didn't work
35 # all the time, and so is better to not bother
36 # since Moose will handle the defaults just
37 # fine anyway.
38 # - SL
39 #( exists $opt->{default} ? (default => $opt->{default}) : () ),
40 },
41 ];
42
33edcaa4 43 my $identifier = lc($opt->{name});
a2099669 44 $identifier =~ s/\W/_/g; # Getopt::Long does this to all option names
45
46 $name_to_init_arg{$identifier} = $opt->{init_arg};
47 }
48
49 return ( \@options, \%name_to_init_arg );
50}
51
33edcaa4 52no Moose::Role; 1;
ef47fe44 53
54__END__
55
56=pod
57
58=head1 NAME
59
33edcaa4 60MooseX::Getopt::GLD - A Moose role for processing command line options with Getopt::Long::Descriptive
ef47fe44 61
62=head1 SYNOPSIS
ef47fe44 63
33edcaa4 64 ## In your class
65 package My::App;
66 use Moose;
ef47fe44 67
33edcaa4 68 with 'MooseX::Getopt::GLD';
ef47fe44 69
33edcaa4 70 has 'out' => (is => 'rw', isa => 'Str', required => 1);
71 has 'in' => (is => 'rw', isa => 'Str', required => 1);
ef47fe44 72
33edcaa4 73 # ... rest of the class here
ef47fe44 74
33edcaa4 75 ## in your script
76 #!/usr/bin/perl
ef47fe44 77
33edcaa4 78 use My::App;
ef47fe44 79
33edcaa4 80 my $app = My::App->new_with_options();
81 # ... rest of the script here
ef47fe44 82
33edcaa4 83 ## on the command line
84 % perl my_app_script.pl -in file.input -out file.dump
ef47fe44 85
33edcaa4 86=head1 DESCRIPTION
ef47fe44 87
88=head1 COPYRIGHT AND LICENSE
89
33edcaa4 90Copyright 2007-2009 by Infinity Interactive, Inc.
ef47fe44 91
92L<http://www.iinteractive.com>
93
94This library is free software; you can redistribute it and/or modify
95it under the same terms as Perl itself.
96
97=cut