Devel-REPL-1.003028
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / LexEnv.pm
CommitLineData
1716b200 1use strict;
2use warnings;
85cd2780 3package Devel::REPL::Plugin::LexEnv;
9d2a4940 4# ABSTRACT: Provide a lexical environment for the REPL
85cd2780 5
5ac98890 6our $VERSION = '1.003028';
54beb05d 7
6a5409bc 8use Devel::REPL::Plugin;
aa8b7647 9use namespace::autoclean;
85cd2780 10use Lexical::Persistence;
11
3a400715 12sub BEFORE_PLUGIN {
13 my $self = shift;
14 $self->load_plugin('FindVariable');
15}
bd67131f 16
85cd2780 17has 'lexical_environment' => (
18 isa => 'Lexical::Persistence',
19 is => 'rw',
85cd2780 20 lazy => 1,
21 default => sub { Lexical::Persistence->new }
22);
23
2bdaa93e 24has '_hints' => (
25 isa => "ArrayRef",
26 is => "rw",
27 predicate => '_has_hints',
28);
29
85cd2780 30around 'mangle_line' => sub {
31 my $orig = shift;
32 my ($self, @rest) = @_;
33 my $line = $self->$orig(@rest);
34 my $lp = $self->lexical_environment;
4d33251a 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)
2bdaa93e 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 );
85cd2780 45};
46
47around '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
6d22063d 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#};
bd67131f 66
85cd2780 671;
cfd1094b 68
69__END__
70
9d2a4940 71=pod
cfd1094b 72
e4761e81 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
cfd1094b 92=cut