On Thu, Nov 25, 2010 at 12:36:57PM +0000, Zefram wrote:
> p p wrote:
> >With DefaultFormatter I can simply do:
> 
> Eww, global variable.  You can do that in your modules, and so can anyone
> else in theirs, but if you both do it and your modules end up in the
> same process then you'll step on each other's toes.
> 
> You really want to find a more convenient way for you to explicitly
> attach a particular formatter to each column that you declare.  Such as
> write a wrapper for the DBIC stuff.

FWIW, I do this for my application which uses Moose DateTime attributes all
over the place (for holding information stored to/from a mysql db), so I
don't ever have to explicitly set the formatter, timezone etc:

class_type 'DateTime';
coerce 'DateTime'
    => from 'Str'
    => via {
        # check for retarded mysql 4.x null timestamps: this will
        # generate a nicer type coercion error than simply parsing directly
        return if $_ eq '0000-00-00 00:00:00';
        my $dt;
        try {
            $dt = DateTime::Format::MySQL->parse_datetime($_);
        }
        catch ($e) {
            confess "DateTime coercion failed: $e";
        }
        $dt->set_formatter('DateTime::Format::MySQL');
        $dt->set_time_zone('UTC');
        $dt;
    };

subtype 'MaybeDateTime' => as 'Maybe[DateTime]';
coerce 'MaybeDateTime'
    => from 'Str'
    => via {
        # check for retarded mysql 4.x null timestamps
        return if $_ eq '0000-00-00 00:00:00';
        my $dt;
        try {
            $dt = DateTime::Format::MySQL->parse_datetime($_);
        }
        catch ($e) {
            cluck "DateTime coercion failed: $e";
        }
        $dt->set_formatter('DateTime::Format::MySQL');
        $dt->set_time_zone('UTC');
        $dt;
    };

my @types = qw(
    DateTime
    MaybeDateTime
);

# create subs in the current namespace for each type constraint.
# e.g. you can call my $val = MyApp::Types::MaybeDateTime->assert_coerce($str);
foreach my $type_name (@types)
{
    my $class = __PACKAGE__;
    my $short_name = $type_name =~ /^\Q$class\E::(.+)/ ? $1 : $type_name;
    Sub::Install::install_sub({
        code => sub {
            Moose::Util::TypeConstraints::find_type_constraint($type_name)
        },
        into => $class,
        as   => $short_name,
    });
}


-- 
     "A society in which consumption has to be artificially stimulated in
    order to keep production going is a society founded on trash and waste,
      and such a society is a house built upon sand." - Dorothy L. Sayers
            .             .            .            .             .
Karen Etheridge, ka...@etheridge.ca       GCS C+++$ USL+++$ P+++$ w--- M++
http://etheridge.ca/                      PS++ PE-- b++ DI++++ e++ h(-)

Reply via email to