| 1 | package Ubic::ServiceLoader; | ||
| 2 | $Ubic::ServiceLoader::VERSION = '1.59'; | ||
| 3 | # ABSTRACT: load service from file | ||
| 4 | |||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | |||
| 8 | |||
| 9 | use Params::Validate qw(:all); | ||
| 10 | use File::Basename; | ||
| 11 | use Ubic::ServiceLoader::Default; | ||
| 12 | |||
| 13 | my %ext2loader; | ||
| 14 | |||
| 15 | sub ext2loader { | ||
| 16 | my $class = shift; | ||
| 17 | my ($ext) = validate_pos(@_, { type => SCALAR, regex => qr/^\w+$/ }); | ||
| 18 | |||
| 19 | return $ext2loader{$ext} if $ext2loader{$ext}; | ||
| 20 | require "Ubic/ServiceLoader/Ext/$ext.pm"; # TODO - improve error message if ext.pm doesn't exist | ||
| 21 | my $loader_class = "Ubic::ServiceLoader::Ext::$ext"; | ||
| 22 | return $loader_class->new; | ||
| 23 | # FIXME - cache loader_class! | ||
| 24 | } | ||
| 25 | |||
| 26 | sub split_service_filename { | ||
| 27 | my $class = shift; | ||
| 28 | my ($filename) = validate_pos(@_, 1); | ||
| 29 | |||
| 30 | my ($service_name, $ext) = $filename =~ /^ | ||
| 31 | ([\w-]+) | ||
| 32 | (?: \.(\w+) )? | ||
| 33 | $/x; | ||
| 34 | return ($service_name, $ext); | ||
| 35 | } | ||
| 36 | |||
| 37 | sub load { | ||
| 38 | my $class = shift; | ||
| 39 | my ($file) = validate_pos(@_, 1); | ||
| 40 | |||
| 41 | my $filename = basename($file); | ||
| 42 | my ($service_name, $ext) = $class->split_service_filename($filename); | ||
| 43 | die "Invalid filename '$file'" unless defined $service_name; | ||
| 44 | |||
| 45 | my $loader; | ||
| 46 | if ($ext) { | ||
| 47 | $loader = $class->ext2loader($ext); | ||
| 48 | } | ||
| 49 | else { | ||
| 50 | $loader = Ubic::ServiceLoader::Default->new; | ||
| 51 | } | ||
| 52 | |||
| 53 | my $service = $loader->load($file); | ||
| 54 | return $service; | ||
| 55 | } | ||
| 56 | |||
| 57 | |||
| 58 | 1; | ||
| 59 | |||
| 60 | __END__ |