Skip to content

Commit

Permalink
update EXAMPLE
Browse files Browse the repository at this point in the history
  • Loading branch information
Ryo Anazawa committed May 18, 2013
1 parent a507d8d commit 21c05ed
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 32 deletions.
33 changes: 15 additions & 18 deletions lib/CGI/Header.pm
Expand Up @@ -497,33 +497,30 @@ in this case.
It's up to you to decide how to manage HTTP cookies.
use parent 'CGI::Header';
use CGI::Cookie;
# Add cookie() attribute which defaults a reference to an empty hash.
# The keys of the hash are the cookies' names, and their corresponding
# values are a plain string, e.g., "$header->cookie->{ID} = 123456"
sub cookie {
$_[0]->{cookie} ||= {};
}
# The cookies() method behaves like Mojo::Message::Response#cookies:
# $cookies = $header->cookies;
# $header->cookies( ID => 123456 );
# $header->cookies({ name => 'ID', value => 123456 });
# The 'cookies' property defaults to an arrayref
sub cookies {
$_[0]->header->{cookies} ||= [];
}
# Override as_string() to create and set CGI::Cookie objects right before
# stringifying header props.
sub as_string {
my $self = shift;
my $query = $self->query;
my $cookies = $self->cookies;
my $cookies = $self->header->{cookies} ||= [];
while ( my ($name, $value) = each %{$self->cookie} ) {
push @{$cookies}, $query->cookie( $name => $value );
return $cookies unless @_;
if ( ref $_[0] eq 'HASH' ) {
push @$cookies, map { CGI::Cookie->new($_) } @_;
}
else {
push @$cookies, CGI::Cookie->new( @_ );
}
$self->SUPER::as_string;
$self;
}
=head2 WORKING WITH CGI::Simple
Since L<CGI::Simple> is "a relatively lightweight drop in
Expand Down
25 changes: 11 additions & 14 deletions t/20_cookie.t
Expand Up @@ -4,31 +4,28 @@ use Test::More tests => 1;

package CGI::Header::Extended;
use base 'CGI::Header';

sub cookie {
$_[0]->{cookie} ||= {};
}
use CGI::Cookie;

sub cookies {
$_[0]->header->{cookies} ||= [];
}

sub as_string {
my $self = shift;
my $query = $self->query;
my $cookies = $self->cookies;
my $cookies = $self->header->{cookies} ||= [];

return $cookies unless @_;

while ( my ($name, $value) = each %{$self->cookie} ) {
push @{$cookies}, $query->cookie( $name => $value );
if ( ref $_[0] eq 'HASH' ) {
push @$cookies, map { CGI::Cookie->new($_) } @_;
}
else {
push @$cookies, CGI::Cookie->new( @_ );
}

$self->SUPER::as_string;
$self;
}

package main;

my $header = CGI::Header::Extended->new;

$header->cookie->{ID} = 123456;
$header->cookies( ID => 123456 );

like $header->as_string, qr{Set-Cookie: ID=123456};

0 comments on commit 21c05ed

Please sign in to comment.