Commit | Line | Data |
445e5e31 |
1 | package DBIx::Class::InflateColumn::DateTime; |
2 | |
3 | use strict; |
4 | use warnings; |
5 | use base qw/DBIx::Class/; |
6 | |
0b375b68 |
7 | =head1 NAME |
8 | |
9 | DBIx::Class::InflateColumn::DateTime - Auto-create DateTime objects from datetime columns. |
10 | |
11 | =head1 SYNOPSIS |
12 | |
13 | Load this component and then declare one or more |
14 | columns to be of the datetime datatype. |
15 | |
16 | package Event; |
17 | __PACKAGE__->load_components(qw/InflateColumn::DateTime/); |
18 | __PACKAGE__->add_columns( |
19 | starts_when => { data_type => 'datetime' } |
20 | ); |
21 | |
22 | Then you can treat the specified column as a L<DateTime> object. |
23 | |
24 | print "This event starts the month of ". |
25 | $event->starts_when->month_name(); |
26 | |
27 | =head1 DESCRIPTION |
28 | |
29 | This module figures out the type of DateTime::Format::* class to |
30 | inflate/deflate with based on the type of DBIx::Class::Storage::DBI::* |
31 | that you are using. If you switch from one database to a different |
32 | one your code will continue to work without modification. |
33 | |
34 | =cut |
35 | |
445e5e31 |
36 | __PACKAGE__->load_components(qw/InflateColumn/); |
37 | |
38 | __PACKAGE__->mk_group_accessors('simple' => '__datetime_parser'); |
39 | |
9b83fccd |
40 | =head2 register_column |
41 | |
42 | Chains with the L<DBIx::Class::Row/register_column> method, and sets |
43 | up datetime columns appropriately. This would not normally be |
44 | directly called by end users. |
45 | |
46 | =cut |
47 | |
445e5e31 |
48 | sub register_column { |
49 | my ($self, $column, $info, @rest) = @_; |
50 | $self->next::method($column, $info, @rest); |
51 | if ($info->{data_type} =~ /^datetime$/i) { |
52 | $self->inflate_column( |
53 | $column => |
54 | { |
55 | inflate => sub { |
56 | my ($value, $obj) = @_; |
57 | $obj->_datetime_parser->parse_datetime($value); |
58 | }, |
59 | deflate => sub { |
60 | my ($value, $obj) = @_; |
61 | $obj->_datetime_parser->format_datetime($value); |
62 | }, |
63 | } |
64 | ); |
65 | } |
66 | } |
67 | |
68 | sub _datetime_parser { |
69 | my $self = shift; |
70 | if (my $parser = $self->__datetime_parser) { |
71 | return $parser; |
72 | } |
73 | my $parser = $self->result_source->storage->datetime_parser(@_); |
74 | return $self->__datetime_parser($parser); |
75 | } |
76 | |
77 | 1; |
0b375b68 |
78 | __END__ |
79 | |
80 | =head1 SEE ALSO |
81 | |
82 | =over 4 |
83 | |
84 | =item More information about the add_columns method, and column metadata, |
85 | can be found in the documentation for L<DBIx::Class::ResultSource>. |
86 | |
87 | =back |
88 | |
89 | =head1 AUTHOR |
90 | |
91 | Matt S. Trout <mst@shadowcatsystems.co.uk> |
92 | |
93 | =head1 CONTRIBUTORS |
94 | |
95 | Aran Deltac <bluefeet@cpan.org> |
96 | |
97 | =head1 LICENSE |
98 | |
99 | You may distribute this code under the same terms as Perl itself. |
100 | |