avoid indexing headaches with DateTimeX
[gitmo/MooseX-Types-DateTime.git] / lib / MooseX / Types / DateTimeX.pm
1 package MooseX::Types::DateTimeX;
2
3 use strict;
4 use warnings;
5
6 use DateTime;
7 use DateTime::Duration;
8 use DateTimeX::Easy; 
9 use Time::Duration::Parse ();
10 use MooseX::Types::DateTime;  
11 use MooseX::Types::Moose qw/Num HashRef Str/;
12 use MooseX::Types -declare => [qw( DateTime Duration)];
13
14   
15 =head1 NAME
16
17 MooseX::Types::DateTimeX - Extensions to L<MooseX::Types::DateTime>
18
19 =head1 SYNOPSIS
20
21         package MyApp::MyClass;
22         
23     use MooseX::Types::DateTimeX qw( DateTime );
24         
25     has created => (
26         isa => DateTime,
27         is => "rw",
28         coerce => 1,
29     );
30         
31         my $instance = MyApp::MyClass->new(created=>'January 1, 1980');
32         print $instance->created->year; # is 1980
33         
34         ## Coercions from the base type continue to work as normal.
35         my $instance = MyApp::MyClass->new(created=>{year=>2000,month=>1,day=>10});
36
37 Please see the test case for more example usage.
38
39 =head1 DESCRIPTION
40
41 This module builds on L<MooseX::Types::DateTime> to add additional custom
42 types and coercions.  Since it builds on an existing type, all coercions and
43 constraints are inherited.
44
45 =head1 SUBTYPES
46
47 This module defines the following additional subtypes.
48
49 =head2 DateTime
50
51 Subtype of 'DateTime'.  Adds an additional coercion from strings.
52
53 Uses L<DateTimeX::Easy> to try and convert strings, like "yesterday" into a 
54 valid L<DateTime> object.  Please note that due to ambiguity with how different
55 systems might localize their timezone, string parsing may not always return 
56 the most expected value.  IN general we try to localize to UTC whenever
57 possible.  Feedback welcomed!
58
59 =cut
60
61 subtype DateTime,
62   as 'DateTime'; ## From MooseX::Types::DateTime
63
64 coerce DateTime,
65   @{find_type_constraint('DateTime')->coercion->type_coercion_map},
66   from Str,
67   via { DateTimeX::Easy->new($_, default_time_zone=>'UTC') };
68
69
70 =head2 Duration
71
72 Subtype of 'DateTime::Duration' that coerces from a string.  We use the module
73 L<Time::Duration::Parse> to attempt this.
74
75 =cut
76
77 subtype Duration,
78   as 'DateTime::Duration'; ## From MooseX::Types::Duration
79
80 coerce Duration,
81   @{find_type_constraint('DateTime::Duration')->coercion->type_coercion_map},
82   from Str,
83   via { 
84         DateTime::Duration->new( 
85                 seconds => Time::Duration::Parse::parse_duration($_)
86         )}; 
87  
88
89 =head1 AUTHOR
90
91 John Napiorkowski E<lt>jjn1056 at yahoo.comE<gt>
92
93 =head1 LICENSE
94
95         Copyright (c) 2008 John Napiorkowski.
96         
97         This program is free software; you can redistribute
98         it and/or modify it under the same terms as Perl itself.
99
100 =cut
101
102 1;