On Mon, Nov 08, 2010 at 10:12:16PM +0000, Adam Guthrie wrote:
> Hi,
>
> I've the following class
>
> package AG::Dirs;
>
> use Moose;
> use namespace::autoclean;
> use Path::Class::Dir;
> use MooseX::Types::Path::Class;
>
> has 'root_dir' => ( isa => 'Path::Class::Dir', is => 'ro', coerce => 1,
> required => 1 );
>
> has [ qw/
> upload_dir
> dynamic_data_cache_dir
> static_image_dir
> user_image_dir
> / ]
> => ( isa => 'Path::Class::Dir', is => 'ro', coerce => 1, lazy_build => 1 );
>
> sub _build_update_dir { $_[0]->root_dir->subdir('upload') };
> sub _build_dynamic_data_cache_dir {
> $_[0]->root_dir->subdir('dynamic_data_cache') };
> sub _build_static_image_dir { $_[0]->root_dir->subdir('static_image') };
> sub _build_user_image_dir { $_[0]->root_dir->subdir('user_image') };
>
> __PACKAGE__->meta->make_immutable;
>
> Is there a better way than the multiple _build functions? A function that
> uses the attribute name perhaps?
>
> Any help much appreciated,
>
> Adam
for $dir in (qw(upload dynamic_data_cache static_image user_image)) {
has $dir => (
isa => 'Path::Class::Dir',
is => 'ro',
coerce => 1,
lazy_build => 1,
);
__PACKAGE__->meta->add_method("_build_${dir}_dir" => sub {
$_[0]->root_dir->subdir($dir);
});
}
or
for $dir in (qw(upload dynamic_data_cache static_image user_image)) {
has $dir => (
isa => 'Path::Class::Dir',
is => 'ro',
coerce => 1,
default => sub {
$_[0]->root_dir->subdir($dir);
}
);
}
if you don't really need predicates or clearers.
-doy