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