about summary refs log tree commit diff
diff options
context:
space:
mode:
authorfranck cuny <franck@lumberjaph.net>2010-06-02 11:38:07 +0200
committerfranck cuny <franck@lumberjaph.net>2010-06-02 11:38:07 +0200
commit1c4c26d1a82b81df4571568b21d919418f3355fa (patch)
tree8101972ebe99086860fd72266d160509631a2e98
parenthttp_request and api_base_url are defined in this role (diff)
downloadnet-http-api-1c4c26d1a82b81df4571568b21d919418f3355fa.tar.gz
use MX::Net::API::Parser to handle serialization
-rw-r--r--lib/MooseX/Net/API/Role/Serialization.pm48
1 files changed, 48 insertions, 0 deletions
diff --git a/lib/MooseX/Net/API/Role/Serialization.pm b/lib/MooseX/Net/API/Role/Serialization.pm
new file mode 100644
index 0000000..b36955c
--- /dev/null
+++ b/lib/MooseX/Net/API/Role/Serialization.pm
@@ -0,0 +1,48 @@
+package MooseX::Net::API::Role::Serialization;
+
+use Try::Tiny;
+use Moose::Role;
+
+has serializers => (
+    traits     => ['Hash'],
+    is         => 'rw',
+    isa        => 'HashRef[MooseX::Net::API::Parser]',
+    default    => sub { {} },
+    auto_deref => 1,
+    handles    => {
+        _add_serializer => 'set',
+        _get_serializer => 'get',
+    },
+);
+
+sub deserialize {
+    my ($self, $content, $list_of_formats) = @_;
+
+    foreach my $format (@$list_of_formats) {
+        my $s = $self->_get_serializer($format)
+          || $self->_load_serializer($format);
+        next unless $s;
+        my $result = try { $s->decode($content) };
+        return $result if $result;
+    }
+}
+
+sub serialize {
+    my ($self, $content) = @_;
+    my $s = $self->_get_serializer($self->api_format);
+    my $result = try { $s->encode($content) };
+    return $result if $result;
+}
+
+sub _load_serializer {
+    my $self   = shift;
+    my $format = shift || $self->api_format;
+    my $parser = "MooseX::Net::API::Parser::" . uc($format);
+    if (Class::MOP::load_class($parser)) {
+        my $o = $parser->new;
+        $self->_add_serializer($format => $o);
+        return $o;
+    }
+}
+
+1;