I have written a class for pattern that I found myself using several times.
Before I release it to the CPAN I would appreciate any feedback on the name, the documentation and it's usefulness.
The pod:
NAME
Data::Inflator - Convert arbitrary scalars to/from objects repeatably
SYNOPSIS
use NetAddr::IP;
my $ip = Data::Inflator->new( class => 'NetAddr::IP' );
# get back NetAddr::IP->new('192.168.1.250')
my $addr_obj = $ip->inflate('192.168.1.250');
#... do all kinds of fun things with $addr_obj
# does default stringify on NetAddr::IP object
my $addr_str = $tp->deflate($addr_obj);
use Time::Piece;
my $di_fancy = Data::Inflator->new( class => 'Time::Piece',
inflate => sub {
Time::Piece->str
+ptime(shift, "%Y-%m-%d")
},
deflate => 'ymd' );
my $time_piece = $tp->inflate('2006-05-31'); # calls the inflate
+sub and passes '2006-05-31'
$time_piece += ONE_DAY;
my $date_string = $tp->deflate($time_piece); # calls ymd method on
+ Time::Piece object
DESCRIPTION
An class for creating objects that can inflate a scalar to object and
+deflate that same object back to a
scalar reproducibly. The major database mappers that I have used (Clas
+s::DBI, Rose::DB::Object, Hibernate,
etc) have the concept of inflating a value stored in a database into a
+ more useful object upon retrieval.
For example a string representing a date is extracted from postgresql
+or oracle and coerced "automagically"
into a DateTime or Time::Piece object.
When it's time to save our information back to the database the object
+ has to be in a format that is compatible
with the column type. Producing this form is "deflating."
Inflate values from:
* command line arguments
* configuration files
* web forms
CLASS METHODS
new
my $ip_inflator = Data::Inflator->new( class => 'NetAddr::IP'
+);
my $time_inflator = Data::Inflator->new( class => 'Time::Piece',
inflate => sub { Time::Pi
+ece->strptime(shift, "%Y-%m-%d") },
deflate => 'ymd' );
The 'class' parameter is required and must be the name of a perl packa
+ge.
Objects of the 'class' class are instantiated via '$class->new(@args)'
+ or the method defined by the 'inflate' parameter.
'inflate' can be a string or a subroutine reference. When 'inflate' is
+ a subroutine it will be executed, and will be passed the
value and the object of the classClass::DBI object as arguments.
'deflate' follows the same rules as inflate. If no deflate is specifie
+d Data::Inflator attempts to stringify the object
so unless your class overrides stringification you'll want to provie a
+ deflate argument.
OBJECT METHODS
inflate
Pass in the value to be inflated and receive an object.
my $ip = $ipfactory->inflate('192.168.1.1')
deflate
Pass in the object to be inflated and receive an string.
my $ipstring = $ipfactory->deflate( $ip )