Jeffrey++

Ah yes, I always forget about the coercion too. I do this sometimes as well, the only issue being that you sometimes want to still have access to the original information, etc. Which in some cases you can just do via delegation on the constructed object.

- Stevan


On Nov 26, 2009, at 5:32 PM, 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


Reply via email to