fREWdiculous!
21 Jan
So after discussing this problem with the inimitable ribasushi we came up with a good solution. It’s not quite generic, but it solves the current problem very nicely. First, we subclass DateTime:
1 2 3 4 5 6 7 8 9 | package MTSI::DateTime; use strict; use warnings; use parent 'DateTime'; sub TO_JSON { shift->ymd } 1; |
Next, in the base class we use for all of our Result classes in our Schema, we override _inflate_to_datetime to rebless the returned value into our subclass:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
And lastly, in our JSON view, we ensure that convert_blessed is on so that json will automatically call our TO_JSON method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package ACD::View::JSON; use Moose; extends 'Catalyst::View::JSON'; use JSON::XS (); has encoder => ( is => 'ro', lazy_build => 1, ); sub _build_encoder { my $self = shift; return JSON::XS->new->utf8->convert_blessed; } sub encode_json { my($self, $c, $data) = @_; $self->encoder->encode($data); } 1; |
And that’s all there is to it! Thanks Perl for allowing me to rebless my objects
Leave a reply