Search code examples
perlmoose

How can I die upon accessing a non-existing key in a deep Hoh as Moose attribute?


I have a Moose object with an attribute that is hash:

has 'custom_fields' => (
    traits  => [qw( Hash )],
    isa     => 'HashRef',
    builder => '_build_custom_fields',
    handles => {
        custom_field        => 'accessor',
        has_custom_field    => 'exists',
        custom_fields       => 'keys',
        has_custom_fields   => 'count',
        delete_custom_field => 'delete',
    },
);

around 'custom_field' => sub {
    my $orig  = shift // confess;
    my $self  = shift // confess;
    my $field = shift // confess;

    confess "Attempt accessing non-existing custom field '$field'"
        unless ( @_ or $self->has_custom_field($field) );

    $self->$orig( $field, @_ );
};

his works well for simple, one level hashes. Now I would like to allow deep hashes (hash of hashes of hashes ...) and still confess whenever an access to a non-existing (possibly deep) key is attempted.

UPDATE Perhaps somehow use Data::Diver?


Solution

  • Generally I'd say, if you have a complex data structure that you want to handle in an object oriented manner, you should turn the data structure into a tree of objects. With Moose coercions this can be modeled rather transparently as well.