2010-04-27 52 views
2

我有一個類(ActorClue),其中定義了三個attr_accessor。還有其他類需要的其他常見字段,所以我將這些公共字段放在模塊中(BaseClueProperties)。我在我的ActorClue類中包含該模塊。來自類和包含模塊的屬性列表

下面的代碼採樣:

module BaseClueProperties 
    attr_accessor :image_url 
    attr_accessor :summary_text 
end 

################ 
class BaseClue 

    # http://stackoverflow.com/questions/2487333/fastest-one-liner-way-to-list-attr-accessors in-ruby  
    def self.attr_accessor(*vars) 
    @attributes ||= [] 

    @attributes.concat vars 

    super(*vars) 
    end 

    def self.attributes 
    @attributes 
    end 

    def attributes 
    self.class.attributes 
    end 

end 

############### 

class ActorClue < BaseClue 

    attr_accessor :actor_name 
    attr_accessor :movie_name 
    attr_accessor :directed_by 

    include BaseClueProperties 

    ..... 
end 

我實例上面有以下:

>> gg = ActorClue.new 
=> #<ActorClue:0x23bf784> 
>> gg.attributes 
=> [:actor_name, :movie_name, :directed_by] 

爲什麼只返回:ACTOR_NAME,:MOVIE_NAME和:directed_by不包括:IMAGE_URL和:summary_text?

我修改了BaseClueProperties閱讀以下內容:

module BaseClueProperties 
    BaseClue.attr_accessor :image_url 
    BaseClue.attr_accessor :summary_text 
end 

但仍具有相同的結果。

對於爲什麼my:image_url和:summary_text屬性未添加到我的@attributes集合有任何想法?

回答

5

我不能保證我對原因的描述是正確的,但下面的代碼應該可以解決問題。我相信你正在向模塊添加屬性而不是它所包含的類。無論如何用以下內容替換你的模塊應該解決這個問題。

module BaseClueProperties 

    def self.included(base) 
    base.send :attr_accessor, :image_url 
    base.send :attr_accessor, :summary_text 
    end 

end 

這應該會導致包含對象在包含模塊時定義attribute_accessors。

相關問題