From: Stevan Little Date: Mon, 21 Sep 2009 04:08:25 +0000 (-0400) Subject: adding another example and some docs X-Git-Tag: 0.92~8 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=e7597637a2d3c7fddf0e0ea651e3216f8c461c95;p=gitmo%2FMoose.git adding another example and some docs --- diff --git a/lib/Moose/Util/TypeConstraints.pm b/lib/Moose/Util/TypeConstraints.pm index b5ff3f7..2341102 100644 --- a/lib/Moose/Util/TypeConstraints.pm +++ b/lib/Moose/Util/TypeConstraints.pm @@ -1150,11 +1150,30 @@ Perl pretty printer dispatching over the core Moose types. => sub { die "I don't know what $_ is" }; } +Or a simple JSON serializer: + + sub to_json { + my $x = shift; + match_on_type $x => + HashRef => sub { + my $hash = shift; + '{ ' . (join ", " => map { + '"' . $_ . '" : ' . to_json( $hash->{ $_ } ) + } sort keys %$hash ) . ' }' }, + ArrayRef => sub { + my $array = shift; + '[ ' . (join ", " => map { to_json( $_ ) } @$array ) . ' ]' }, + Num => sub { $_ }, + Str => sub { '"'. $_ . '"' }, + Undef => sub { 'null' }, + => sub { die "$_ is not acceptable json type" }; + } + Based on a mapping of C<$type> to C<\&action>, where C<$type> can be either a string type or a L object, and C<\&action> is a CODE ref, this function will dispatch on the first match for C<$value>. It is possible to have a catch-all at the end -in the form of a C<\&default> CODE ref +in the form of a C<\&default> CODE ref. =back diff --git a/t/040_type_constraints/036_match_type_operator.t b/t/040_type_constraints/036_match_type_operator.t index 3728ea8..f5fa5ad 100644 --- a/t/040_type_constraints/036_match_type_operator.t +++ b/t/040_type_constraints/036_match_type_operator.t @@ -3,7 +3,7 @@ use strict; use warnings; -use Test::More tests => 23; +use Test::More tests => 25; use Test::Exception; use Moose::Util::TypeConstraints; @@ -174,6 +174,42 @@ is( '... got the right pretty printed values' ); +# simple JSON serializer + +sub to_json { + my $x = shift; + match_on_type $x => + HashRef => sub { + my $hash = shift; + '{ ' . (join ", " => map { + '"' . $_ . '" : ' . to_json( $hash->{ $_ } ) + } sort keys %$hash ) . ' }' }, + ArrayRef => sub { + my $array = shift; + '[ ' . (join ", " => map { to_json( $_ ) } @$array ) . ' ]' }, + Num => sub { $_ }, + Str => sub { '"'. $_ . '"' }, + Undef => sub { 'null' }, + => sub { die "$_ is not acceptable json type" }; +} + +is( + to_json( { one => 1, two => 2 } ), + '{ "one" : 1, "two" : 2 }', + '... got our valid JSON' +); + +is( + to_json( { + one => [ 1, 2, 3, 4 ], + two => undef, + three => "Hello World" + } ), + '{ "one" : [ 1, 2, 3, 4 ], "three" : "Hello World", "two" : null }', + '... got our valid JSON' +); + + # some error cases sub not_enough_matches {