Re: Calling class methods from a metaclass

[email protected] ("Dan Harbin")
Newsgroups perl.moose
Message-ID <[email protected]>
On Fri, Jun 13, 2008 at 12:10 PM, Todd Hepler <[email protected]> wrote:
> Dan Harbin wrote:
>>
>> The following:
>>
>>    #!/usr/bin/env perl
>>    use strict;
>>    use warnings;
>>
>>    package MyClass;
>>    {
>>      use Moose;
>>
>>      sub hello_class {
>>        my $class = shift;
>>        return  "Hello $class\n";
>>      }
>>    }
>>
>>    print "1: ", MyClass->hello_class(), "\n";
>>
>>    my $myclass = Class::MOP::get_metaclass_by_name('MyClass');
>>
>>    print "2: ", $myclass->hello_class(), "\n";
>>
>
> For your example, this should work:
>
>      print "2: ", $myclass->name->hello_class(), "\n";
>
>
>
> I guess there are kinda 2 ways to think of class methods in Moose.  You can
> do it like your example above, or you could use an object method on the
> metaclass object -- which is what $myclass->hello_class() is trying to call.
>  Perhaps a unifying approach would look like:
>
> {
>
>    package MyMetaClass;
>
>    use Moose;
>    BEGIN { extends 'Moose::Meta::Class'; }
>
>    sub hello_class {
>        my $self = shift;
>        return "Hello " . $self->name . "\n";
>    }
> }
>
> {
>
>    package MyClass;
>    use metaclass 'MyMetaClass';
>    use Moose;
>
>    sub hello_class {
>        my $class = shift;
>
>        # delegate to the metaclass
>        return $class->meta->hello_class;
>    }
> }
>
> print "1: ", MyClass->hello_class(), "\n";
> my $myclass = Class::MOP::get_metaclass_by_name('MyClass');
> print "2: ", $myclass->hello_class(), "\n";
> print "3: ", $myclass->name->hello_class(), "\n";
>
> But that does seems a bit... un-concise.
>
> -Todd
>
>

Thanks Todd, that worked (the first way - I didn't try the second).
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.