2010-12-15 87 views
2

正如标题所暗示的,我希望能够做这样的事情在我的课:如何在Moose中定义默认属性属性值?

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, 
     ... 
    ); 

    ... 
} 

也就是说,规定将适用于所有属性定义,除非覆盖了一些默认的属性值。

回答

3

这听起来像你想写一些自定义属性声明,它提供了一些默认选项。这是覆盖在Moose::Cookbook::Extending::Recipe1,如:

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, 
    ); 
} 

然后在你的类:

package MyApp::SomeObject; 

use MyApp::Moosish; 

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

# remaining class definition as normal. 
+0

为了澄清,我认为'的'has_table'功能$ name'使用给定'has_table“ my_attr'=>(...)'?另外,你的意思是'...-> build_import_methods'而不是'...-> setup_import_methods'? – gvkv 2010-12-16 12:22:56

+0

@gvkv:没错 - has_table只是一个常规函数,其中第一个参数是属性名称,其余参数是属性选项字段和值。 我的意思是setup_import_methods - build_import_methods返回coderefs,它允许你修改它们,但是你必须自己安装它们 - 这对于这样一个简单的情况并不是必需的。 – Ether 2010-12-16 19:56:10