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