Jumat, 21 Mei 2010

Custom class dumping for Data::Dump

I'm using DateTime objects a lot these days: anytime I get some date/time data from outside of Perl, the first thing I do is convert them to DateTime object, to avoid calculation/formatting hassle ahead.



However, the dumps are not pretty.



% perl -MDateTime -MData::Dump -e'dd [DateTime->now]'



[

bless({

formatter => undef,

local_c => {

day => 21,

day_of_quarter => 51,

day_of_week => 5,

day_of_year => 141,

hour => 8,

minute => 55,

month => 5,

quarter => 2,

second => 36,

year => 2010,

},

local_rd_days => 733913,

local_rd_secs => 32136,

locale => bless({

"default_date_format_length" => "medium",

"default_time_format_length" => "medium",

en_complete_name => "English United States",

en_language => "English",

en_territory => "United States",

id => "en_US",

native_complete_name => "English United States",

native_language => "English",

native_territory => "United States",

}, "DateTime::Locale::en_US"),

offset_modifier => 0,

rd_nanosecs => 0,

tz => bless({ name => "UTC" }, "DateTime::TimeZone::UTC"),

utc_rd_days => 733913,

utc_rd_secs => 32136,

utc_year => 2011,

}, "DateTime"),

]



It gets worse when you have some records each with DateTime object in it.



That's why I added a couple of mechanisms to allow us to custom a class' dump.



$ perl -Ilib -MDateTime -MData::Dump -e'$Data::Dump::CUSTOM_CLASS_DUMPERS{"DateTime"} = sub { "$_[0]" }; dd [DateTime->now]'

[2010-05-21T08:57:45]



or:



$ perl -Ilib -MDateTime -MData::Dump -e'package DateTime; sub dump { "$_[0]" }; package main; dd [DateTime->now]'

[2010-05-21T08:58:09]

I know some other dumper in CPAN probably has this ability, but I like Data::Dump's output.

If you want to take a look at a couple of small patches to Data::Dump: http://github.com/sharyanto/data-dump

I've also contacted Gisle Aas to ask what he thinks of it.

2 komentar:

  1. I would absolutely love such a mechanism.

    I find quite often I have little objects that only contain one or two items of interesting data, plus a reference (possibly idnrectly) to, say, the IO::Async object that is the root core of the program, that references (indirectly) everything else. Data::Dump'ing one of those isn't pretty. Having an ability to customise the output for these stub objects and ignore that reference would be highly useful indeed.

    BalasHapus
  2. This is a great idea. I hope it makes it upstream.

    BalasHapus

Catatan: Hanya anggota dari blog ini yang dapat mengirim komentar.