I'd like to convert an accessor-builder to a moose Trait.
It's called like so:

__PACKAGE__->generate_attribute_accessor( 'foo' );
# generates methods foo() and foo_xml()

The code for the current generator looks something like this:

sub generate_attribute_accessor {
    my $caller = shift;

    for my $name (@_) {
        my $sub = sub {
            my $self = shift;

            if (@_) {
                $self->attributes->{$name} = mogrify( $_[0] );
            }
            else {
                return $self->attributes->{$name};
            }
        };

        my $xml_sub = sub {
            my $self = shift;

            return $self->$name( xml_mogrify( @_ ) );
        }

        no strict 'refs';
        *{"$caller\::$name"}       = $sub
        *{"$caller\::${name}_xml"} = $xml_sub;
    }
}

I'd like to be able to define it something like this:

has 'foo' => ( is = > 'rw', traits => ['XmlAttrMogrifier'] );

There are 2 aspect of this I'd like advice on.

First, the fact that foo() doesn't read / write to a slot on $self,
but to a hash-key on $self->attributes.
I thought I might be able to build something based on
MooseX::DeepAccessors, but that would require a syntax such as:
    has 'attributes' => ( is => 'rw', traits => ['Hash'],
deep_accessors => { foo => { ... } } );
which adds the short-cut method names to the 'attributes' definition.
I don't think this is feasible, because my class needs to be able to
define the 'attributes' accessor with it's choice of short-cut
methods, and also consume Roles which will define their own choice of
short-cut methods.
This would require both the class and all Roles doing a "has
'attributes'" which will cause clashes.
So, basically: is there a way to be able to write "has 'foo'" with a
Trait to get this behaviour?

Secondly, the fact that it generates 2 methods - I could live with
having to write 2 explicit declarations and 2 different Traits:
    has 'foo' => ( is => 'rw', traits => ['AttrMogrifier'] );
    has 'foo_xml' => ( is => 'rw', traits => ['XMLAttrMogrifier'] );
but if I could legitimately get has() to generate multiple methods,
that'd be much better.

Any pointers to documentation or existing modules to copy from would
be most welcome!

Cheers,
Carl

Reply via email to