| 1 | package Amon2::Plugin::Web::Flash; | ||
| 2 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 3 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 1 | ▶ | use utf8; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | |||
| 6 | our $VERSION = '0.05'; | ||
| 7 | |||
| 8 | 0 | ▶ | use Amon2::Util; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 9 | |||
| 10 | sub init { | ||
| 11 | my ($class, $c, $conf) = @_; | ||
| 12 | my $webpkg = ref $c || $c; | ||
| 13 | |||
| 14 | my $key = $conf->{session_key} || 'flash'; | ||
| 15 | my $new_key = $key . "_new"; | ||
| 16 | my $flash; | ||
| 17 | my $new_flash; | ||
| 18 | |||
| 19 | Amon2::Util::add_method($webpkg, flash => sub { | ||
| 20 | my ($self, $flash_key, $value) = @_; | ||
| 21 | |||
| 22 | # getter | ||
| 23 | return $flash unless $flash_key; | ||
| 24 | return $flash->{$flash_key} unless $value; | ||
| 25 | |||
| 26 | # setter | ||
| 27 | $new_flash->{$flash_key} = $value; | ||
| 28 | return $value; | ||
| 29 | }); | ||
| 30 | |||
| 31 | Amon2::Util::add_method($webpkg, flash_now => sub { | ||
| 32 | my ($self, $flash_key, $value) = @_; | ||
| 33 | # getter. same as flash | ||
| 34 | return $self->flash($flash_key) unless $value; | ||
| 35 | |||
| 36 | # setter | ||
| 37 | $flash->{$flash_key} = $value; | ||
| 38 | return $value; | ||
| 39 | }); | ||
| 40 | |||
| 41 | Amon2::Util::add_method($webpkg, flash_keep => sub { | ||
| 42 | my ($self, $flash_key) = @_; | ||
| 43 | unless ($flash_key) { | ||
| 44 | for my $k (keys %$flash) { | ||
| 45 | $self->flash($k => $self->flash($k)); | ||
| 46 | } | ||
| 47 | return; | ||
| 48 | } | ||
| 49 | $self->flash($flash_key => $self->flash($flash_key)); | ||
| 50 | }); | ||
| 51 | |||
| 52 | Amon2::Util::add_method($webpkg, flash_discard => sub { | ||
| 53 | my ($self, $flash_key, $value) = @_; | ||
| 54 | unless ($flash_key) { | ||
| 55 | $flash = {}; | ||
| 56 | return; | ||
| 57 | } | ||
| 58 | undef $flash->{$flash_key}; | ||
| 59 | }); | ||
| 60 | |||
| 61 | $c->add_trigger(BEFORE_DISPATCH => sub { | ||
| 62 | my $c = shift; | ||
| 63 | $c->session->remove($key); | ||
| 64 | $flash = $c->session->get($new_key) || {}; | ||
| 65 | $new_flash = {}; | ||
| 66 | }); | ||
| 67 | |||
| 68 | $c->add_trigger(AFTER_DISPATCH => sub { | ||
| 69 | my $c = shift; | ||
| 70 | $c->session->set($new_key, $new_flash); | ||
| 71 | }); | ||
| 72 | } | ||
| 73 | |||
| 74 | 1; | ||
| 75 | |||
| 76 | __END__ | ||