rewritten working with no regexps
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / Packages.pm
1 package Devel::REPL::Plugin::Packages;
2
3 use Moose::Role;
4 use vars qw($PKG_SAVE);
5
6 has 'current_package' => (
7   isa      => 'Str',
8   is       => 'rw',
9   default  => 'Devel::REPL::Plugin::Packages::DefaultScratchpad',
10   lazy     => 1
11 );
12
13 around 'wrap_as_sub' => sub {
14   my $orig = shift;
15   my ($self, @args) = @_;
16   my $line = $self->$orig(@args);
17   # prepend package def before sub { ... }
18   return q!package !.$self->current_package.qq!;\n${line}!;
19 };
20
21 around 'mangle_line' => sub {
22   my $orig = shift;
23   my ($self, @args) = @_;
24   my $line = $self->$orig(@args);
25   # add a BEGIN block to set the package around at the end of the sub
26   # without mangling the return value (we save it off into a global)
27   $line .= '; BEGIN { $Devel::REPL::Plugin::Packages::PKG_SAVE = __PACKAGE__; }';
28   return $line;
29 };
30
31 after 'execute' => sub {
32   my ($self) = @_;
33   # if we survived execution successfully, save the new package out the global
34   $self->current_package($PKG_SAVE);
35 };
36
37 around 'eval' => sub {
38   my $orig = shift;
39   my ($self, @args) = @_;
40   # localise the $PKG_SAVE global in case of nested evals
41   local $PKG_SAVE;
42   return $self->$orig(@args);
43 };
44
45 package Devel::REPL::Plugin::Packages::DefaultScratchpad;
46
47 # declare empty scratchpad package for cleanliness
48
49 1;