Ado
view release on metacpan or search on metacpan
lib/Ado/Command.pm view on Meta::CPAN
package Ado::Command;
use Mojo::Base 'Mojolicious::Command';
use Mojo::Util qw(decamelize decode);
has args => sub { {} };
has name => sub { (ref $_[0]) =~ /(\w+)$/ && return $1 };
#default initialization for each Ado command
sub init {
my $self = shift;
$self->args->{do} ||= $self->name;
$self->config->{actions} ||= [$self->name];
return 1;
}
# Current Ado::Command home
has home => sub {
my $class_file = Mojo::Util::class_to_path(ref($_[0]) || $_[0]);
my ($root) = $INC{$class_file} =~ m{^(.+?)/[^/]+/$class_file$}x;
return $root;
};
sub _get_command_config {
my ($self) = @_;
state $app = $self->app;
my $name = $self->name;
#first try (global config) !!!autovivification
my $config = $app->config->{commands} && $app->config->{commands}->{$name};
$config && return $config;
#second try (command specific configuration file)
my $conf_file = $app->home->rel_file('/etc/commands/' . decamelize($name) . '.conf');
if ($config = eval { Mojolicious::Plugin::Config->new->load($conf_file, {}, $app) }) {
return $config;
}
else {
$app->log->warn(
"Could not load configuration from file $conf_file! " . decode('UTF-8', $@));
return {};
}
}
sub config {
my ($self, $key) = @_;
state $config = $self->_get_command_config();
return $key
? $config->{$key}
: $config;
}
#a default run method
sub run {
my ($self, @args) = @_;
#0. initialize
$self = ref($self) ? $self : $self->new();
$self->init(@args) || return;
#1. run
my $action = $self->args->{do};
if ($action && $self->can($action)) {
$self->$action();
}
else {
Carp::croak
"Command action '$action' was not found! Please implement it! Supported actions should be: "
. join(', ', @{$self->config->{actions} || []});
}
return;
}
1;
=pod
=encoding utf8
=head1 NAME
Ado::Command - Ado namespace for Mojo commands!
=head1 DESCRIPTION
Ado::Command is the base class for eventual functionality that we
can run directly from the commandline or from controllers.
In this class we can put common functionality shared among all the commands.
=head1 ATTRIBUTES
L<Ado::Command> inherits all attributes from L<Mojolicious::Command> and implements the following new ones.
( run in 2.945 seconds using v1.01-cache-2.11-cpan-5837b0d9d2c )