I’m fairly new to both Moose and Rose::DB::Object. and have been poking around trying to find a simple way to marry the two. Delegation and roles do the trick here.
I created a parameterized role, so that I could tell the role what Rose::DB::Object-derived class to delegate to.
package My::DB::Role;
use MooseX::Role::Parameterized;parameter 'table' => (
is => 'ro',
isa => 'Str',
);role {
my $p = shift;my $class =
$p->table =~ /^My::DB/
? $p->table
: join '::', 'My::DB', $p->table
;eval "require $class";
$class->import;has 'db_obj' => (
is => 'rw',
isa => $class,
handles => [ $class->meta->column_names, qw(save load delete) ],
default => sub {
$class->new;
},
);
};no Moose;
1;
In my consuming class, I specify the role and the shortened name of the Rose::DB::Object-derived class:
package My::Product;
use Moose;with 'Prixing::DB::Role' => { table => 'Product'};
1;
With this little setup, I have working code:
use Test::More;use_ok('My::Product');
my $product = My::Product->new;
$product->id(1);
$product->load;note $product->created_at;
done_testing;
This outputs:
ok 1 – use My::Product;
# 2011-04-09T09:03:20
1..1
This is not thoroughly tested; I just did this tonight. But this looks like the way to go.
Further reading:
- Kate Yoak posts a comment about her solution at Rohan Almeida’s blog (now listed as an attack site by Google, which I find odd). Link to very fierce attack site; you have been warned.
- Inheritance from Rose::DB::Object has been possible since Moose 1.15, which introduced the
-meta_nametouse Moose. Renaming Moose’smetaneatly sidesteps the Rose::DB::Object method of the same name.
Yeah, my blog was compromised and unfortunately had to move the entire blog onto a new server. I still have a backup of my post but not the comments (which are the real stuff)