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