Skip to content

Moose with role already attached

July 25, 2009

OK so adding Singleton Method to you class is nice and easy with:

use Moose;
with 'MooseX::SingletonMethod';


But wouldn’t it be even nicer if you could replace the two lines with something like:

use MyMoose;


Well you can by applying the role to the base object (Moose::Object) like so:

package MyMoose;

use Moose ();
use Moose::Exporter;
use Moose::Util::MetaRole;

Moose::Exporter->setup_import_methods( also => 'Moose' );

sub init_meta {
    my %options = @_;

    my $meta = Moose->init_meta( %options );

        for_class => $options{ for_class },
        roles     => [ 'MooseX::SingletonMethod' ],  # <= my roles

    return $meta;



And then we can create Moose class and use it like so:

package Baz;
use MyMoose;
has 'name' => ( is => 'rw', isa => 'Str' );

package main;

my $baz = Baz->new( name => 'baz' );

$baz->add_singleton_method( hello => sub { 'hello ' . $_[0]->name } ); 

say $baz->hello;   # => 'hello baz'


Of course you don’t need to stop with just adding MooseX::SingletonMethod role only… add all your favourite roles in there!

For more info see Moose::Cookbook::Extending::Recipe2


3 Comments leave one →
  1. July 25, 2009 2:47 pm

    Really useful and clear! Thanks. I wonder how this works with MooseX::Declare….

    • July 28, 2009 8:33 am

      Thanks John.

      Re: MooseX::Declare… Yes I wonder how this would work to πŸ˜‰

      Getting into Devel::Declare is on my (long!) list of things todo. I guess we need to be able to tell MX::Declare to use a different base class which could look like this?….

      use MooseX::Declare (base_class => ‘MyMoose’);



  1. Changing MooseX::SingletonMethod (a little bit!) « transfixed but not dead!

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

%d bloggers like this: