2011-06-03 12 views
7

__PACKAGE__->meta->get_attribute('foo') का उपयोग करके, आप किसी दिए गए वर्ग में foo विशेषता परिभाषाओं तक पहुंच सकते हैं, जो उपयोगी हो सकता है।मूस (पर्ल): आधार कक्षाओं में पहुंच विशेषता परिभाषा

#!perl 
package Bla; 
use Moose; 
has bla => is => 'ro', isa => 'Str'; 
has hui => is => 'ro', isa => 'Str', required => 1; 
no Moose; __PACKAGE__->meta->make_immutable; 

package Blub; 
use Moose; 
has bla => is => 'ro', isa => 'Str'; 
has hui => is => 'ro', isa => 'Str', required => 0; 
no Moose; __PACKAGE__->meta->make_immutable; 

package Blubbel; 
use Moose; 
extends 'Blub'; 
no Moose; __PACKAGE__->meta->make_immutable; 

package main; 
use Test::More; 
use Test::Exception; 

my $attr = Bla->meta->get_attribute('hui'); 
is $attr->is_required, 1; 

$attr = Blub->meta->get_attribute('hui'); 
is $attr->is_required, 0; 

$attr = Blubbel->meta->get_attribute('hui'); 
is $attr, undef; 
throws_ok { $attr->is_required } 
    qr/Can't call method "is_required" on an undefined value/; 
diag 'Attribute aus Basisklassen werden hier nicht gefunden.'; 

done_testing; 

इस छोटे से कोड नमूना इसका सबूत के रूप में, हालांकि, इस का उपयोग करने के लिए इस्तेमाल नहीं किया जा सकता आधार वर्ग है, जो भी मेरी विशेष मामले के लिए और अधिक उपयोगी होगा में निर्धारित विशेषताएं। क्या मैं चाहता हूं कि हासिल करने का कोई तरीका है?

उत्तर

9

नोट कि get_attribute सुपर-क्लास खोज नहीं करता है, उस के लिए आप उपयोग करना find_attribute_by_name

की जरूरत है - Class::MOP::Class docs। और वास्तव में इस कोड से गुजरता है:

my $attr = Bla->meta->find_attribute_by_name('hui'); 
is $attr->is_required, 1; 

$attr = Blub->meta->find_attribute_by_name('hui'); 
is $attr->is_required, 0; 

$attr = Blubbel->meta->find_attribute_by_name('hui'); 
is $attr->is_required, 0; 
+0

यह काम करता है phantastic, धन्यवाद! :-) – Lumi

संबंधित मुद्दे