2011-01-12 24 views
1

我正在編寫一個插件,其中我在插件中動態定義了一個新的關係。下面如何獲取保存在實例變量中的模型的屬性

module AttachDocumentsAs 
    @as = nil 
    def attach_documents_as(*attachment_as) 
     attachment_as = attachment_as.to_a.flatten.compact.map(&:to_sym) 
     @as   = attachment_as.first 
     class_inheritable_reader(@as) 

     class_eval do 
      has_many @as, :as => :attachable, :class_name=>"AttachDocuments::Models::AttachedDocument" 
      accepts_nested_attributes_for @as 
     end 
    end 
end 

現在示例代碼給出任何模式,我把它作爲

class Person < AtiveRecord::Base 
    attach_documents_as :financial_documents 
end 

現在要訪問要訪問這個類的屬性,重載initialize方法這樣

def initialize(*args) 
    super(*args) 
    "#{@as}".build 
end 

但它沒有獲得必需的屬性,任何人都可以幫助我。我想建立這種關係並設置一些初始值。

等待所有你們的指導方針。

回答

0

您可能會混淆@as類實例變量,該變量僅適用於Person的類方法,而@as實例變量僅適用於此類的實例。我知道,即使這個解釋聽起來有點複雜。

每個對象都有實例變量,而一個類只是一種對象類型。這個類的實例也是對象,它們有自己的獨立實例變量。爲了從類的實例中獲取類實例變量,您需要一個閱讀器方法,就像您定義的那樣。也許你的意思是:

def initialize(*args) 
    super(*args) 

    # self.class.as returns something like :financial_documents, so use this method 
    # to return a scope to build in. 
    send(self.class.as).build 
end 

你使用@as的方式表明您已經習慣了像PHP或Perl,你可以去參考它就像你可能會${$as}。在Ruby中,您通常會將字符串或符號引用到類或方法中。

它看起來像你試圖將符號轉換爲方法調用,並通過send完成。

如果你試圖將字符串轉換成類,您使用的字符串,Rails環境的特徵constantize方法。

+0

我用 class_inheritable_reader(@as) class_inheritable_reader(:atd_as) write_inheritable_attribute(:atd_as,@as) 現在裏面初始化我可以得到它作爲 self.send(self.send( :atd_as)) 但現在的問題是調用構建它 self.send(self.send(:atd_as))建立 不起作用。 –

相關問題