morgon has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I'd like to sweeten some classes with a spoonful of syntactic sugar and wonder if it is possible (and how :-) to achieve the following in Moose:

package Hubba; use Moose -traits => 'WithBubba'; has a; has b; bubba "zappa"; # <- this method should be imported
So what I want is a trait that implements a method ("bubba") and imports this method into the namespace of every class that uses this trait.

Evidently I could use something like

__PACKAGE__->meta->bubba("zappa");
But I find that ugly ... is there a nicer way?

Many thanks!

Replies are listed 'Best First'.
Re: Moose: Importing methods via Traits
by bruno (Friar) on Apr 27, 2009 at 17:56 UTC
    You could use a Role:

    package DoesBubba; use Moose::Role; sub bubba { ... } 1;

    Then in your class:

    package Hubba; use Moose; with 'DoesBubba'; # rest of your class here.

    The 'bubba' method will be composed into your 'Hubba' class (and any other that consumes this role).

      You could use a Role
      Ok, maybe I made myself not clear.

      I do not want a method on the Hubba-class that would be available to it's instances, but I want a method on it that I can call (in the same way as let's say the Moose-supplied method "has" is called) at package-load time to associate a class with a piece of information.

      As an example think about the name of a database-table where instances of this class will get persisted as in Moose::Cookbook::Meta::Recipe5.

      My question then is simply is there a way to avoid the uglyness (in my eyes at least) of doing something like " __PACKAGE__->meta->table('User')"

Re: Moose: Importing methods via Traits
by KSURi (Monk) on Apr 27, 2009 at 19:18 UTC
    Also you can use Moose::Exporter to setup methods which will be directly exported to a caller package. As for me, I prefer using Roles as bruno said above.
      Thanks. Moose::Exporter is exactly what I have been looking for.