I recently came across an excellent article on the “Nine traits of the veteran Unix admin”, it’s all so true…
Moose role hackery
February 8, 2011For quite a while now I have wanted to have the ability to apply a Moose role without actually loading any of the associated code. I’ve finally come up with a solution which seems to do exactly what I need.
For a bit of background, Moose roles are what is often referred to in object-oriented programming as “interfaces”. They are used to declare that a class is guaranteed to implement a particular behaviour (attributes and/or methods) as part of its API.
A commonly used role which is available on CPAN is MooseX::ConfigFromFile which is used to declare that a class has the new_with_config
and get_config_from_file
methods. These are used to set the values of attributes from a configuration file. This works well in conjunction with other roles, such as MooseX::Getopt, which can detect when the ConfigFromFile
role is implemented and load the values for attributes from either the command-line or a specified configuration file.
The problem is that the MooseX::ConfigFromFile
code is a little bit peculiar and has a dependency on MooseX::Types::Path::Class
(and thus MooseX::Types
and Path::Class
amongst others) which are not usually essential and lead to memory bloat for no good reason.
So, here is my solution, add these two lines:
my $extra_role = Moose::Meta::Role->initialize('MooseX::ConfigFromFile'); __PACKAGE__->meta->add_role($extra_role);
I can use this to state that my own configuration loader module does everything that the MooseX::ConfigFromFile
role requires but I do not need to load (or even have installed) the MooseX::ConfigFromFile
module file itself. This seems to work equally well when applied to a role or a class.