Hey, thanks. I often do this in BUILD with a set of if statements depending on the parameters to the constructor - this is much more elegant.
Dan On 27/11/2009, at 11:32 AM, Jeffrey Ray wrote: > Dan Horne wrote: >> Yes - I often need user, pass and dsn strings for a DBI connection or a >> DBI::db object. What would be the best pattern to deal with such cases if >> one were to generalise it? >> > > I often take care of this using type coercion: > > package Object; > use Moose; > use Moose::Util::TypeConstraints; > > class_type 'DBI::db'; > > coerce 'DBI::db' > => from 'ArrayRef' > => via { DBI->connect(@$_) } > > coerce 'DBI::db' > => from 'HashRef' > => via { DBI->connect(@{$_}{qw/dsn username password/}) } > > has 'dbh' => ( > isa => 'DBI::db', > coerce => 1, > ); > > package main; > > $object = Object->new(dbh => [qw/dbh:string username password]); > > or > > $object = Object->new(dbh => {dsn => ..., username => ..., password => ...}); > > or > > $object = Object->new(dbh => DBI->connect(...)); > > will all produce an $object with a dbh that is a DBI::db object >