File Coverage

lib/Ubic/ServiceLoader/Ext/json.pm
Criterion Covered Total %
statement 41 42 97.6
branch 9 14 64.2
condition 2 2 100.0
subroutine 8 8 100.0
pod 2 2 100.0
total 62 68 91.1


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