How can I flexibly add data to Moose objects?

后端 未结 4 1300
野性不改
野性不改 2020-12-17 00:30

I\'m writing a module for a moose object. I would like to allow a user using this object (or myself...) add some fields on the fly as he/she desires. I can\'t define these f

4条回答
  •  情话喂你
    2020-12-17 01:04

    I would probably do this via native traits:

    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',
        },
    );
    
    sub _build_custom_fields { {} }
    

    On an object you'd use this like the following:

    my $val = $obj->custom_field('foo');           # get field value
    $obj->custom_field('foo', 23);                 # set field to value
    
    $obj->has_custom_field('foo');                 # does a specific field exist?
    $obj->has_custom_fields;                       # are there any fields?
    
    my @names = $obj->custom_fields;               # what fields are there?
    my $value = $obj->delete_custom_field('foo');  # remove field value
    

    A common use-case for stuff like this is adding optional introspectable data to exception and message classes.

提交回复
热议问题