| 1 | use v5.10; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | package Meerkat::Types; | ||
| 6 | # ABSTRACT: Moose types for Meerkat | ||
| 7 | |||
| 8 | our $VERSION = '0.016'; | ||
| 9 | |||
| 10 | use MooseX::Types -declare => [qw(MeerkatDateTime)]; | ||
| 11 | use MooseX::Storage::Engine; | ||
| 12 | |||
| 13 | use aliased 'Meerkat::DateTime' => 'MDT'; | ||
| 14 | use DateTime; | ||
| 15 | use Types::Standard qw/:types/; | ||
| 16 | |||
| 17 | subtype MeerkatDateTime, as MDT; | ||
| 18 | |||
| 19 | coerce MeerkatDateTime, ( | ||
| 20 | #<<< No perltidy | ||
| 21 | from Num, via { MDT->new( epoch => $_ ) }, | ||
| 22 | from InstanceOf ['DateTime'], via { MDT->new( epoch => $_->epoch ) }, | ||
| 23 | from InstanceOf ['DateTime::Tiny'], via { MDT->new( epoch => $_->DateTime->epoch ) }, | ||
| 24 | from InstanceOf ['BSON::Time'], via { MDT->new( epoch => $_->epoch ) }, | ||
| 25 | #>>> | ||
| 26 | ); | ||
| 27 | |||
| 28 | # We "collapse" MeerkatDateTime to a DateTime object so that MongoDB will then | ||
| 29 | # translate it to the correct internal type. On inflation, we take the epoch | ||
| 30 | # value it gives and turn that into the Meerkat::DateTime proxy | ||
| 31 | |||
| 32 | MooseX::Storage::Engine->add_custom_type_handler( | ||
| 33 | MeerkatDateTime, | ||
| 34 | ( | ||
| 35 | expand => sub { MDT->new( epoch => "$_[0]" ) }, | ||
| 36 | collapse => sub { DateTime->from_epoch( epoch => $_[0]->epoch ) }, | ||
| 37 | ) | ||
| 38 | ); | ||
| 39 | |||
| 40 | 1; | ||
| 41 | |||
| 42 | |||
| 43 | # vim: ts=4 sts=4 sw=4 et: | ||
| 44 | |||
| 45 | __END__ |