2010-10-23 77 views
1

phaylon's answer to "How can I flexibly add data to Moose objects?",假設我有以下駝鹿屬性:如何修改駝鹿屬性句柄?

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 { {} } 

現在,假設我想發牢騷,如果想讀(但不能寫)到一個不存在的自定義字段。我被phaylon建議使用around修飾符來包裝custom_field。我在Moose文檔中的各種示例之後嘗試使用around修飾符,但無法確定如何修改句柄(而不僅僅是對象方法)。

另外,是否有另一種方法來實現這個croak-if-try-to-read-nonexisting-key?

回答

6

他們仍然只是由穆斯生成的方法。你可以這樣做:

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

    confess "No $field" unless @_ or $self->has_custom_field($field); 

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

(。croak是不是在此刻方法修飾符非常有用它只是將指向你在內部穆斯代碼)

其實,你並不需要使用around爲此。使用before更簡單:

before 'custom_field' => sub { 
    my $self = shift; 
    my $field = shift; 

    confess "No $field" unless @_ or $self->has_custom_field($field); 
}; 
+0

@David B,'handles'正在創建標準的對象方法。一個對象不能有兩個同名的方法。它怎麼知道你打來的是哪一個? (Perl 5沒有multimethods。) – cjm 2010-10-23 20:18:48

+0

+1謝謝cjm。我試圖編輯我對你的評論,但是意外刪除了它。爲了記錄,我問了'如果兩個屬性具有相同名稱的句柄會發生什麼情況'。顯然這是不可能的。再次感謝! – 2010-10-23 20:32:13

+2

@David只是爲了澄清,'handles'選項是爲了讀作動詞'句柄',而不是名詞'句柄'。正如在「這個屬性*處理這些方法」中那樣,而不是「這個屬性有這些句柄」。這是一個授權工具。 – hobbs 2010-10-23 20:51:56