Merge branch 'master' into psgi
[catagits/Catalyst-Runtime.git] / lib / Catalyst / ScriptRole.pm
1 package Catalyst::ScriptRole;
2 use Moose::Role;
3 use MooseX::Types::Moose qw/Str Bool/;
4 use Pod::Usage;
5 use MooseX::Getopt;
6 use Catalyst::Engine::Loader;
7 use MooseX::Types::LoadableClass qw/LoadableClass/;
8 use namespace::autoclean;
9
10 with 'MooseX::Getopt' => {
11     -excludes => [qw/
12         _getopt_spec_warnings
13         _getopt_spec_exception
14         _getopt_full_usage
15     /],
16 };
17
18 has application_name => (
19     traits   => ['NoGetopt'],
20     isa      => Str,
21     is       => 'ro',
22     required => 1,
23 );
24
25 has loader_class => (
26     isa => LoadableClass,
27     is => 'ro',
28     coerce => 1,
29     default => 'Catalyst::Engine::Loader',
30     documentation => 'The class to use to detect and load the PSGI engine',
31 );
32
33 has _loader => (
34     isa => 'Plack::Loader',
35     default => sub {
36         shift->loader_class->new
37     },
38     handles => {
39         load_engine => 'load',
40         autoload_engine => 'auto',
41     },
42     lazy => 1,
43 );
44
45 sub _getopt_spec_exception {}
46
47 sub _getopt_spec_warnings {
48     shift;
49     warn @_;
50 }
51
52 sub _getopt_full_usage {
53     my $self = shift;
54     pod2usage();
55     exit 0;
56 }
57
58 sub run {
59     my $self = shift;
60     $self->_run_application;
61 }
62
63 sub _application_args {
64     ()
65 }
66
67 sub _plack_loader_args {
68     my @app_args = shift->_application_args;
69     return (port => $app_args[0]);
70 }
71
72 sub _run_application {
73     my $self = shift;
74     my $app = $self->application_name;
75     Class::MOP::load_class($app);
76     my $server;
77     if (my $e = $self->can('_plack_engine_name') ) {
78         $server = $self->load_engine($self->$e, $self->_plack_loader_args);
79     }
80     else {
81         $server = $self->autoload_engine($self->_plack_loader_args);
82     }
83     $app->run($self->_application_args, $server);
84 }
85
86 1;
87
88 =head1 NAME
89
90 Catalyst::ScriptRole - Common functionality for Catalyst scripts.
91
92 =head1 SYNOPSIS
93
94     package MyApp::Script::Foo;
95     use Moose;
96     use namespace::autoclean;
97
98     with 'Catalyst::ScriptRole';
99
100     sub _application_args { ... }
101
102 =head1 DESCRIPTION
103
104 Role with the common functionality of Catalyst scripts.
105
106 =head1 METHODS
107
108 =head2 run
109
110 The method invoked to run the application.
111
112 =head1 ATTRIBUTES
113
114 =head2 application_name
115
116 The name of the application class, e.g. MyApp
117
118 =head1 SEE ALSO
119
120 L<Catalyst>
121
122 L<MooseX::Getopt>
123
124 =head1 AUTHORS
125
126 Catalyst Contributors, see Catalyst.pm
127
128 =head1 COPYRIGHT
129
130 This library is free software, you can redistribute it and/or modify
131 it under the same terms as Perl itself.
132
133 =cut