Code, test, docs.
Andrew Rodland [Tue, 27 Oct 2009 09:48:02 +0000 (09:48 +0000)]
lib/Catalyst/Plugin/Session.pm
t/lib/SessionTestApp/Controller/Root.pm
t/live_accessor.t [new file with mode: 0644]

index bc9eb24..1288875 100644 (file)
@@ -425,10 +425,21 @@ sub validate_session_id {
 sub session {
     my $c = shift;
 
-    $c->_session || $c->_load_session || do {
+    my $session = $c->_session || $c->_load_session || do {
         $c->create_session_id_if_needed;
         $c->initialize_session_data;
     };
+
+    if (@_) {
+      my $new_values = @_ > 1 ? { @_ } : $_[0];
+      croak('session takes a hash or hashref') unless ref $new_values;
+
+      for my $key (keys %$new_values) {
+        $session->{$key} = $new_values->{$key};
+      }
+    }
+
+    $session;
 }
 
 sub keep_flash {
@@ -678,6 +689,13 @@ requests.
 This method will automatically create a new session and session ID if none
 exists.
 
+You can also set session keys by passing a list of key/value pairs or a
+hashref.
+
+    $c->session->{foo} = "bar";      # This works.
+    $c->session(one => 1, two => 2); # And this.
+    $c->session({ answer => 42 });   # And this.
+
 =item session_expires
 
 =item session_expires $reset
index 948adc6..36033be 100644 (file)
@@ -67,4 +67,25 @@ sub user_agent : Global {
     $c->res->output('UA=' . $c->req->user_agent);
 }
 
+sub accessor_test : Global {
+    my ( $self, $c ) = @_;
+
+    $c->session(
+        one => 1,
+        two => 2,
+    );
+
+    $c->session( {
+            three => 3,
+            four => 4,
+        },
+    );
+
+    $c->session->{five} = 5;
+
+    for my $key (keys %{ $c->session }) {
+        $c->res->write("$key: " . $c->session->{$key} . "\n");
+    }
+}
+
 1;
diff --git a/t/live_accessor.t b/t/live_accessor.t
new file mode 100644 (file)
index 0000000..62e522b
--- /dev/null
@@ -0,0 +1,35 @@
+#!/usr/bin/perl
+#
+use strict;
+use warnings;
+
+use Test::More;
+
+BEGIN {
+    eval { require Catalyst::Plugin::Session::State::Cookie; Catalyst::Plugin::Session::State::Cookie->VERSION(0.03) }
+      or plan skip_all =>
+      "Catalyst::Plugin::Session::State::Cookie 0.03 or higher is required for this test";
+
+    eval {
+        require Test::WWW::Mechanize::Catalyst;
+        Test::WWW::Mechanize::Catalyst->VERSION(0.51);
+    }
+    or plan skip_all =>
+        'Test::WWW::Mechanize::Catalyst >= 0.51 is required for this test';
+
+    plan tests => 4;
+}
+
+use lib "t/lib";
+use Test::WWW::Mechanize::Catalyst "SessionTestApp";
+
+my $ua = Test::WWW::Mechanize::Catalyst->new;
+
+$ua->get_ok("http://localhost/accessor_test", "Set session vars okay");
+
+$ua->content_contains("two: 2", "k/v list setter works okay");
+
+$ua->content_contains("four: 4", "hashref setter works okay");
+
+$ua->content_contains("five: 5", "direct access works okay");
+