Commit | Line | Data |
1716b200 |
1 | use strict; |
2 | use warnings; |
85cd2780 |
3 | package Devel::REPL::Plugin::LexEnv; |
4 | |
6a5409bc |
5 | use Devel::REPL::Plugin; |
aa8b7647 |
6 | use namespace::autoclean; |
85cd2780 |
7 | use Lexical::Persistence; |
8 | |
3a400715 |
9 | sub BEFORE_PLUGIN { |
10 | my $self = shift; |
11 | $self->load_plugin('FindVariable'); |
12 | } |
bd67131f |
13 | |
85cd2780 |
14 | has 'lexical_environment' => ( |
15 | isa => 'Lexical::Persistence', |
16 | is => 'rw', |
85cd2780 |
17 | lazy => 1, |
18 | default => sub { Lexical::Persistence->new } |
19 | ); |
20 | |
2bdaa93e |
21 | has '_hints' => ( |
22 | isa => "ArrayRef", |
23 | is => "rw", |
24 | predicate => '_has_hints', |
25 | ); |
26 | |
85cd2780 |
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; |
4d33251a |
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) |
2bdaa93e |
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 | ); |
85cd2780 |
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 | |
6d22063d |
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 | #}; |
bd67131f |
63 | |
85cd2780 |
64 | 1; |
cfd1094b |
65 | |
66 | __END__ |
67 | |
68 | =head1 NAME |
69 | |
70 | Devel::REPL::Plugin::LexEnv - Provide a lexical environment for the REPL |
71 | |
e4761e81 |
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 | |
cfd1094b |
91 | =cut |
92 | |