MooseX::AttributeTree 0.04

Inherit attribute values like HTML+CSS does

  Add it to your Download Basket!

 Add it to your Watch List!


Rate it!
send us
an update
Perl Artistic License 
Christopher J. Madsen
ROOT \ System \ Benchmarks
Classes can inherit attributes from their parent classes. But sometimes you want an attribute to be able to inherit its value from a parent object. For example, that's how CSS styles work in HTML.

MooseX::AttributeTree is a Perl module that allows you to apply the TreeInherit trait to any attribute in your class. This changes the way the attribute's accessor method works. When reading the attribute's value, if no value has been set for the attribute in this object, the accessor will return the value from the parent object (which might itself be inherited).

The parent object does not need to be the same type as the child object, but it must have a method with the same name as the attribute's accessor method (unless you supply a fetch_method). (The parent's method may be an attribute accessor method, but it doesn't have to be.) If the parent doesn't have the right method, you'll get a runtime error if the child tries to call it.

By default, MooseX::AttributeTree expects to get the parent object by calling the object's parent method. However, you can use any method to retrieve the link by passing the appropriate parent_link to the TreeInherit trait:

 has ancestor => (
 is => 'rw',
 isa => 'Object',
 weak_ref => 1,

 has value => (
 is => 'ro',
 traits => [ TreeInherit => { parent_link => 'ancestor' } ],

If the method returns undef, then inheritance stops and the accessor will behave like a normal accessor. (Normally, parent_link will be the name of an attribute accessor method, but it doesn't have to be.)

Sometimes it's not convenient for the parent object to have a separate method for each attribute that a child object might want to inherit. In that case, you can supply a fetch_method to the TreeInherit trait.

 has other_value => (
 is => 'ro',
 traits => [ TreeInherit => { fetch_method => 'get_inherited' } ],

With fetch_method, the inherited value will come from


instead of the usual


If your attribute has a predicate method, it reports whether the attribute has been set on that object. The predicate has no knowledge of any value that might be inherited from a parent. This means that $object->has_value may return false even though $object->value would return a value (inherited from the parent).

Likewise, the attribute's clearer method (if any) would clear the attribute only on this object, and would never affect a parent object.


 package MyClass;
 use Moose;
 use MooseX::AttributeTree ();

 has parent => (
 is => 'rw',
 isa => 'Object',
 weak_ref => 1,

 has value => (
 is => 'rw',
 traits => [qw/TreeInherit/],

Last updated on February 3rd, 2012


#attribute values #Perl module #Moose #attribute #values #tree

Add your review!