开发者

How do I define default attribute property values in Moose?

开发者 https://www.devze.com 2023-01-30 13:22 出处:网络
As the title suggests, I\'d like to be able to do something like this in my class: use MooseX::Declare;

As the title suggests, I'd like to be able to do something like this in my class:

use MooseX::Declare;

class MyClass {
    default_attribute_propeties(
        is       => 'ro',
        lazy     => 1,
        required => 1,
    );

    has [qw( some standard props )] => ();

    has 'override_default_props' => (
        is  开发者_运维知识库     => 'rw',
        required => 0,
        ...
    );

    ...
}

That is, define some default property values that will apply to all attribute definitions unless overridden.


It sounds like you want to write some custom attribute declarations, that provide some default options. This is covered in Moose::Cookbook::Extending::Recipe1, e.g.:

package MyApp::Mooseish;

use Moose ();
use Moose::Exporter;

Moose::Exporter->setup_import_methods(
    install     => [ qw(import unimport init_meta) ],
    with_meta   => ['has_table'],
    also        => 'Moose',
);

sub has_table
{
    my ($meta, $name, %config) = @_;

    $meta->add_attribute(
        $name,

        # overridable defaults.
        is => 'rw',
        isa => 'Value', # any defined non-reference; hopefully the caller
                        # passed their own type, which will override
                        # this one.
        # other options you may wish to supply, or calculate based on
        # other arguments passed to this function...

        %config,
    );
}

And then in your class:

package MyApp::SomeObject;

use MyApp::Moosish;

has_table => (
    # any normal 'has' options;
    # will override the defaults.
);

# remaining class definition as normal.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号