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