| 1 | package Ubic::ServiceLoader::Ext::json; | ||
| 2 | $Ubic::ServiceLoader::Ext::json::VERSION = '1.59'; | ||
| 3 | # ABSTRACT: loader for json-style configs | ||
| 4 | |||
| 5 | |||
| 6 | use strict; | ||
| 7 | use warnings; | ||
| 8 | |||
| 9 | use parent qw( Ubic::ServiceLoader::Base ); | ||
| 10 | |||
| 11 | use JSON; | ||
| 12 | |||
| 13 | { | ||
| 14 | # support the compatibility with JSON.pm v1 just because we can | ||
| 15 | # see also: Ubic::Persistent | ||
| 16 | no strict; | ||
| 17 | no warnings; | ||
| 18 | sub jsonToObj; *jsonToObj = (*{JSON::from_json}{CODE}) ? \&JSON::from_json : \&JSON::jsonToObj; | ||
| 19 | } | ||
| 20 | |||
| 21 | sub new { | ||
| 22 | my $class = shift; | ||
| 23 | return bless {} => $class; | ||
| 24 | } | ||
| 25 | |||
| 26 | sub load { | ||
| 27 | my $self = shift; | ||
| 28 | my ($file) = @_; | ||
| 29 | |||
| 30 | open my $fh, '<', $file or die "Can't open $file: $!"; | ||
| 31 | my $content = do { local $/; <$fh> }; | ||
| 32 | close $fh or die "Can't close $file: $!"; | ||
| 33 | |||
| 34 | my $config = eval { jsonToObj $content }; | ||
| 35 | unless ($config) { | ||
| 36 | die "Failed to parse $file: $@"; | ||
| 37 | } | ||
| 38 | |||
| 39 | my $module = delete $config->{module} || 'Ubic::Service::SimpleDaemon'; | ||
| 40 | |||
| 41 | my $options = delete $config->{options}; | ||
| 42 | if (keys %$config) { | ||
| 43 | die "Unknown option '".join(', ', keys %$config)."' in file $file"; | ||
| 44 | } | ||
| 45 | |||
| 46 | $module =~ /^[\w:]+$/ or die "Invalid module name '$module'"; | ||
| 47 | eval "require $module"; # TODO - Class::Load? | ||
| 48 | if ($@) { | ||
| 49 | die $@; | ||
| 50 | } | ||
| 51 | |||
| 52 | my @options = (); | ||
| 53 | @options = ($options) if $options; # some modules can have zero options, I guess | ||
| 54 | return $module->new(@options); | ||
| 55 | } | ||
| 56 | |||
| 57 | 1; | ||
| 58 | |||
| 59 | __END__ |