INET connector
[scpubgit/Object-Remote.git] / lib / Object / Remote / ModuleLoader.pm
CommitLineData
542d5b5c 1package Object::Remote::ModuleLoader;
2
3BEGIN {
4 package Object::Remote::ModuleLoader::Hook;
5 use Moo;
624072a8 6 use Object::Remote::Logging qw( :log :dlog );
542d5b5c 7 has sender => (is => 'ro', required => 1);
8
9 # unqualified INC forced into package main
10 sub Object::Remote::ModuleLoader::Hook::INC {
11 my ($self, $module) = @_;
4a9fa1a5 12 log_debug { "Loading $module via " . ref($self) };
3a8356e1 13 my $ret = eval {
daa3054c 14 if (my $code = $self->sender->source_for($module)) {
15 open my $fh, '<', \$code;
16 Dlog_trace { "Module sender successfully sent code for '$module': $code" } $code;
17 return $fh;
18 }
19 log_trace { "Module sender did not return code for '$module'" };
20 return;
ee6a17a6 21 };
3a8356e1 22 if ($@) {
ee6a17a6 23 log_trace { "Module sender blew up - $@" };
3a8356e1 24 if ($@ =~ /Can't locate/) {
daa3054c 25 # Fudge the error messge to make it work with
26 # Module::Runtime use_package_optimistically
27 # Module::Runtime wants - /\ACan't locate \Q$fn\E .+ at \Q@{[__FILE__]}\E line/
710f1c32 28 # We could probably measure and hard-code this but that could easily
29 # be a forwards compatibility disaster, so do a quick search of caller
30 # with a reasonable range; we're already into a woefully inefficient
31 # situation here so a little defensiveness won't make things much worse
3a8356e1 32 foreach my $i (4..20) {
33 my ($package, $file, $line) = caller($i);
34 last unless $package;
35 if ($package eq 'Module::Runtime') {
36 # we want to fill in the error message with the
37 # module runtime module call info.
38 $@ =~ s/(in \@INC.)/$1 at $file line $line/;
39 last;
40 }
ee6a17a6 41 }
daa3054c 42 }
ee6a17a6 43 die $@;
542d5b5c 44 }
ee6a17a6 45 return $ret;
542d5b5c 46 }
47}
48
49use Moo;
50
5e2b2229 51use Object::Remote::Logging qw( :log );
52
542d5b5c 53has module_sender => (is => 'ro', required => 1);
54
55has inc_hook => (is => 'lazy');
56
57sub _build_inc_hook {
58 my ($self) = @_;
5e2b2229 59 log_debug { "Constructing module builder hook" };
37efeb68 60 my $hook = Object::Remote::ModuleLoader::Hook->new(sender => $self->module_sender);
61 log_trace { "Done constructing module builder hook" };
55c0d020 62 return $hook;
542d5b5c 63}
64
65sub BUILD { shift->enable }
66
67sub enable {
4a9fa1a5 68 log_debug { "enabling module loader hook" };
542d5b5c 69 push @INC, shift->inc_hook;
70 return;
71}
72
73sub disable {
74 my ($self) = @_;
4a9fa1a5 75 log_debug { "disabling module loader hook" };
542d5b5c 76 my $hook = $self->inc_hook;
77 @INC = grep $_ ne $hook, @INC;
78 return;
79}
80
81sub DEMOLISH { $_[0]->disable unless $_[1] }
82
831;