summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJesse Luehrs <doy@tozt.net>2012-10-11 13:49:04 -0500
committerJesse Luehrs <doy@tozt.net>2012-10-11 13:49:04 -0500
commitc5ee7923bb6d38f138e58e7da5f9dfaa85bb9721 (patch)
tree642e92b853ebe9bac3888365e1159ddd2de88652
parent04ba3d16bb9db715e009c09f0af807d8d5848263 (diff)
downloadmoosex-validation-doctypes-c5ee7923bb6d38f138e58e7da5f9dfaa85bb9721.tar.gz
moosex-validation-doctypes-c5ee7923bb6d38f138e58e7da5f9dfaa85bb9721.zip
allow serializing the error objects as json
-rw-r--r--lib/MooseX/Validation/Doctypes/Errors.pm9
-rw-r--r--t/json.t40
2 files changed, 49 insertions, 0 deletions
diff --git a/lib/MooseX/Validation/Doctypes/Errors.pm b/lib/MooseX/Validation/Doctypes/Errors.pm
index 023493c..ca4d54d 100644
--- a/lib/MooseX/Validation/Doctypes/Errors.pm
+++ b/lib/MooseX/Validation/Doctypes/Errors.pm
@@ -104,6 +104,15 @@ has extra_data => (
predicate => 'has_extra_data',
);
+sub TO_JSON {
+ my $self = shift;
+
+ return {
+ ($self->has_errors ? (errors => $self->errors) : ()),
+ ($self->has_extra_data ? (extra_data => $self->extra_data) : ()),
+ };
+}
+
__PACKAGE__->meta->make_immutable;
no Moose;
diff --git a/t/json.t b/t/json.t
new file mode 100644
index 0000000..a2abf93
--- /dev/null
+++ b/t/json.t
@@ -0,0 +1,40 @@
+#!/usr/bin/env perl
+use strict;
+use warnings;
+use Test::More;
+
+use Test::Requires 'JSON';
+
+use Moose::Util::TypeConstraints 'find_type_constraint';
+
+use MooseX::Validation::Doctypes;
+
+doctype 'Person' => {
+ id => 'Str',
+ name => 'Str',
+ title => 'Str',
+};
+
+my $JSON = JSON->new->utf8->convert_blessed;
+
+{
+ my $person = find_type_constraint('Person');
+ my $errors = $person->validate({ foo => "bar" });
+
+ is_deeply(
+ $JSON->decode($JSON->encode($errors)),
+ {
+ errors => {
+ id => "invalid value undef for 'id'",
+ name => "invalid value undef for 'name'",
+ title => "invalid value undef for 'title'",
+ },
+ extra_data => {
+ foo => "bar",
+ },
+ },
+ "error objects can be encoded as json"
+ );
+}
+
+done_testing;