Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re^2: Dynamically adding methods to Moo class

by McA (Priest)
on Apr 23, 2014 at 16:14 UTC ( #1083384=note: print w/replies, xml ) Need Help??

in reply to Re: Dynamically adding methods to Moo class
in thread Dynamically adding methods to Moo class

Hi hippo,

thank you for your fast reply. I really hoped that there is a possibility to use this kind of "method installation infrastructure" Moo must have for e.g. to implement the 'has'-declaration. With this declaration you get later an appropriate sub which you can call as method.

For an example use case. Assume you have a simple class:

package Me; use strict; use warnings; use Moo; has 'typ' => ( is => 'ro', required => 1, ); has 'other' => ( is => 'ro', required => 1, ); sub info { my $self = shift; return $self->new( 'typ' => 'INFO', 'other' => "@_", ); }

The method 'info' is just a convenience constructor for the Moo generated constructor 'new'. If I like to do this for several values of 'typ' I would repeat myself. So I hoped to "create" / "generate" these methods more elegant.


Replies are listed 'Best First'.
Re^3: Dynamically adding methods to Moo class
by tobyink (Abbot) on Apr 23, 2014 at 16:41 UTC

    Don't forget that Moo is still Perl. You can still do all the stuff you could normally do using Perl!

    for my $t (qw/ INFO BINFO WINFO SCHMINFO /) { no strict 'refs'; *{lc $t} = sub { my $class = shift; $class->new( typ => $t, other => "@_" ); }; }
    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

      Thank you, Tobyink. That's what I meant with "Or do I have to tweak with the symbol table?" in my initial question. I thought that this kind of functionality is somewhere accessible in a more "formal" manner. A kind of:

      install_method('method_name', sub {});

      Best regards

        Not part of Moo, but ...
        use Sub::Install; Sub::Install::install_sub({ code => sub { ... }, into => $package, as => $subname });
        Link: Sub::Install

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1083384]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2018-05-21 10:11 GMT
Find Nodes?
    Voting Booth?