Getting Moose and Rose::DB::Object to play together

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_name to use Moose. Renaming Moose’s meta neatly sidesteps the Rose::DB::Object method of the same name.
About these ads

One Response to Getting Moose and Rose::DB::Object to play together

  1. 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) :(

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: