changelog bfwg's work
[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/
ee6a17a6 31 # the callstack range is a bit of a guess, we want
32 # to make a reasonable effort, but not spend forever.
33 for(my $i = 4; $i < 20; $i++)
34 {
35 my ($package, $file, $line) = caller($i);
36 last unless $package;
37 if($package eq 'Module::Runtime')
38 {
39 # we want to fill in the error message with the
40 # module runtime module call info.
41 $@ =~ s/(in \@INC.)/$1 at $file line $line/;
42 last;
43 }
44 }
daa3054c 45 }
ee6a17a6 46 die $@;
542d5b5c 47 }
ee6a17a6 48 return $ret;
542d5b5c 49 }
50}
51
52use Moo;
53
5e2b2229 54use Object::Remote::Logging qw( :log );
55
542d5b5c 56has module_sender => (is => 'ro', required => 1);
57
58has inc_hook => (is => 'lazy');
59
60sub _build_inc_hook {
61 my ($self) = @_;
5e2b2229 62 log_debug { "Constructing module builder hook" };
37efeb68 63 my $hook = Object::Remote::ModuleLoader::Hook->new(sender => $self->module_sender);
64 log_trace { "Done constructing module builder hook" };
55c0d020 65 return $hook;
542d5b5c 66}
67
68sub BUILD { shift->enable }
69
70sub enable {
4a9fa1a5 71 log_debug { "enabling module loader hook" };
542d5b5c 72 push @INC, shift->inc_hook;
73 return;
74}
75
76sub disable {
77 my ($self) = @_;
4a9fa1a5 78 log_debug { "disabling module loader hook" };
542d5b5c 79 my $hook = $self->inc_hook;
80 @INC = grep $_ ne $hook, @INC;
81 return;
82}
83
84sub DEMOLISH { $_[0]->disable unless $_[1] }
85
861;