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 {
    shift;
    my %options = @_;

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

    Moose::Util::MetaRole::apply_base_class_roles(
        for_class => $options{ for_class },
        roles     => [ 'MooseX::SingletonMethod' ],  # <= my roles
    );

    return $meta;
}

1;

 

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

/I3az/

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’);

      /I3az/

Trackbacks

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

Leave a reply to draegtun Cancel reply