Making Baby Moose Better

Its Moose day here in the Moose-Pen today.

Still playing about with re-factoring things before I move along too far and what I wan to fix today is this block of code;


package Test::DB::User;
use Moose;
use parent qw(Database::Accessor);
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
my $ops = shift(@_);
return $class->$orig({
view=> {name=>'user'},
elements=>[{view=>'user',
name=>'username'},
{name=>'address',
view=>'user'}],
update_requires_condition=>0,
delete_requires_condition=>0
});
};
1;

You will remember that I was using this in my 10_crud_basic.t test case like this;

use Test::Utils;
use Test::DB::User;
my $utils = Test::Utils->new();
$utils->create_users_table();
my $user = Test::DB::User->new();
my $container = {username=>'user_new',
address =>'address_new'};
eval{
$user->create($utils->connect(),
$container);
};

I wanted to have a reusable hunk of code and provide a good real world example of a class that is using Database::Accessor properly. However looking again at that first block of code I have made a number of Moose boo-boos.

The first that I have mentioned before was that I was overwriting my around BUILDARGS and thus taking removing some rules out of Database::Accessor. More importantly if I am trying to extend Moose in the wrong way.

In Moose when you want to extend a class you should always avoid 'use base' and 'use parent' and instead stick with the Moose 'extends' keyword. I must say that in my rush to get something out I just Aped some early non Moose code and did not even think of that 'extends' keyword.

Today I did have a little time and I figured out how to property extend a Moose class and I realized it is not what I wanted for that 'Test::DB::User' class. In the end I came up with this;


package Test::DB::User;
use Database::Accessor;
use Moose;
has table => ( is => 'ro',
isa => 'Str',
default=>'user');
has fields => ( isa => 'ArrayRef',
is => 'ro',
default => sub { [{view=>'user',
name=>'username'},
{name=>'address',
view=>'user'}] },
);
sub da {
my $self = shift;
my $da = Database::Accessor->new({view=>{name=>$self->table},
elements=>$self->fields,
update_requires_condition=>0,
delete_requires_condition=>0});

}
1;

as a starting point. I did have to make this small adjustment

--my $user = Test::DB::User->new();
++my $db_user = Test::DB::User->new();
++my $user = $db_user->da();

to 10_crud_basic.t and all my tests pass.

A much better way forward me thinks.

linda008a.jpg

Leave a comment

About byterock

user-pic Long time Perl guy, a few CPAN mods allot of work on DBD::Oracle and a few YAPC presentations