aada760c8e044fd95f3d49ba2503c092a965ab9a
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / LexEnv.pm
1 use strict;
2 use warnings;
3 package Devel::REPL::Plugin::LexEnv;
4 # ABSTRACT: Provide a lexical environment for the REPL
5
6 our $VERSION = '1.003029';
7
8 use Devel::REPL::Plugin;
9 use namespace::autoclean;
10 use Lexical::Persistence;
11
12 sub BEFORE_PLUGIN {
13     my $self = shift;
14     $self->load_plugin('FindVariable');
15 }
16
17 has 'lexical_environment' => (
18   isa => 'Lexical::Persistence',
19   is => 'rw',
20   lazy => 1,
21   default => sub { Lexical::Persistence->new }
22 );
23
24 has '_hints' => (
25   isa => "ArrayRef",
26   is => "rw",
27   predicate => '_has_hints',
28 );
29
30 around 'mangle_line' => sub {
31   my $orig = shift;
32   my ($self, @rest) = @_;
33   my $line = $self->$orig(@rest);
34   my $lp = $self->lexical_environment;
35   # Collate my declarations for all LP context vars then add '';
36   # so an empty statement doesn't return anything (with a no warnings
37   # to prevent "Useless use ..." warning)
38   return join('',
39     'BEGIN { if ( $_REPL->_has_hints ) { ( $^H, %^H ) = @{ $_REPL->_hints } } }',
40     ( map { "my $_;\n" } keys %{$lp->get_context('_')} ),
41     qq{{ no warnings 'void'; ''; }\n},
42     $line,
43     '; BEGIN { $_REPL->_hints([ $^H, %^H ]) }',
44   );
45 };
46
47 around 'execute' => sub {
48   my $orig = shift;
49   my ($self, $to_exec, @rest) = @_;
50   my $wrapped = $self->lexical_environment->wrap($to_exec);
51   return $self->$orig($wrapped, @rest);
52 };
53
54 # this doesn't work! yarg. we now just check $self->can('lexical_environment')
55 # in FindVariable
56
57 #around 'find_variable' => sub {
58 #  my $orig = shift;
59 #  my ($self, $name) = @_;
60 #
61 #  return \( $self->lexical_environment->get_context('_')->{$name} )
62 #    if exists $self->lexical_environment->get_context('_')->{$name};
63 #
64 #  return $orig->(@_);
65 #};
66
67 1;
68
69 __END__
70
71 =pod
72
73 =head1 SYNOPSIS
74
75  # in your re.pl file:
76  use Devel::REPL;
77  my $repl = Devel::REPL->new;
78  $repl->load_plugin('LexEnv');
79
80  $repl->lexical_environment->do(<<'CODEZ');
81  use FindBin;
82  use lib "$FindBin::Bin/../lib";
83  use MyApp::Schema;
84  my $s = MyApp::Schema->connect('dbi:Pg:dbname=foo','broseph','elided');
85  CODEZ
86
87  $repl->run;
88
89  # after you run re.pl:
90  $ warn $s->resultset('User')->first->first_name # <-- note that $s works
91
92 =cut