in reply to Re: Re: Date conversion with Class::DBI
in thread Date conversion with Class::DBI

I've never used Class::DBI, but based on what I've read in the docs, i think maybe you aren't fully understanding what cees is trying to say.

According to the docs, you can use has_a to specify a type of object to model a nugget of data, and whenever the value of that nugget is "set", the specified "inflate" method will be called to construct an object of that type, and the specified "deflate" method will be used whenever the object needs to be formatted to insert into the DB.

So you should be able to specify an "inflate" method that parses the string in whatever format(s) you want your users to be able to provide as input, and specify a "deflate" method that stringifies using whatever format your DB wants the date to be in.

The documentation of the "has_a" method has a good example of this.

  • Comment on Re: Re: Re: Date conversion with Class::DBI

Replies are listed 'Best First'.
... Re: Date conversion with Class::DBI
by bsb (Priest) on Jul 07, 2003 at 07:12 UTC
    I may be getting this all wrong but here's my reasoning:

    • has_a sets triggers to inflate a value to an object on both 'select' and 'after_set_$column'.
    • The inflate method converts the nugget of data into an object.
    • In the 'select' case, the nugget comes from the database.
    • In the 'after_set_$col' case, the nugget comes from the user
    I want to use different formats for the user and the database. Maybe has_a could be part of the solution in combination with normalization (which happens prior to 'after_set_$col' and can do format conversion). But like I said, I don't think has_a alone is enough. I'd like to be wrong though.

    I found the docs quite confusing on this, even more so after I started trying to do it.

    The better answer seems to be just to override the accessor/mutator and leave the objects data in the MySQL format. The outside world sees it d/m/y and Class::DBI can ignore it. I should also be able to override all 'date' type accessors during class initialization automatically.

    (I'm not sure if this will play well with validation though).

    sub gp_ref_date { my $self = shift; if(@_) { # setting my $date = shift; if($date =~ m! (\d+) / (\d+) (?:/ (\d+) )+!x) { my $y = $3; $y += ($y < 70) ? 2000 : 1900 if($y < 100); $date = sprintf "%4d-%02d-%02d", $y,$2,$1; } return $self->_gp_ref_date_accessor($date); } else { my $date = $self->_gp_ref_date_accessor(@_); $date =~ s!(\d{4})-(\d\d)-(\d\d)!$3/$2/$1!; return $date; } }