2010-12-15 96 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