2013-05-10 70 views
0

我有一些問題,擴大與後單獨的模塊實例方法類被列入單獨的類定義在Ruby中已經定義的類之後的類的實例方法

module ActsAsCommentable 
    def self.included(commentable) 
    Thread.class_eval do 
     def commentable 
     p "disqusable is #{commentable}" 
     p "disqusable class is #{commentable}" 
     end 
    end 
    end 
end 


class Thread 
    #some code... 
end 

class Asset 
    include ActsAsCommentable 
end 

,現在我想調用這個方法somelike這:

thread = Thread.new 
thread.commentable 

的問題是,當然是沒有用結合包括類eval方法,我可以保存,我想進入ActsAsCommentable模塊類的eval變量,但我不想。有沒有更好的辦法?

我試圖做的,而不是

module ActsAsCommentable 
    def self.included(commentable) 
    class << Thread 
     define_method :commentable do 
     p "disqusable is #{commentable}" 
     p "disqusable class is #{commentable}" 
     end 
    end 
    end 
end 

但正如我猜測這個類的singletone對象創建實例方法,所以我只能通過

Thread.commentable 

再次,沒有約束力調用它。 ..

+1

可評論的[主題](http://ruby-doc.org/core-2.0/Thread.html)?這是什麼瘋狂? 您應該選擇一個更具體的名稱,它不會與併發機制發生衝突。 – 2013-05-10 12:34:36

+0

那麼這實際上是使用disqus模塊,並且有Thread實體,因此,問題不在於此)。在代碼中這個模塊嵌套在Disqus :: Thread中,我只是不想污染示例。但你一般都是對的。 – sandric 2013-05-10 12:38:23

+1

我知道這個問題不是關於它的,這正是我在閱讀你的代碼時所想到的:) – 2013-05-10 12:43:52

回答

0

如果我理解正確,您需要能夠訪問Thread擴展中的commentable變量,對嗎?

如果是這樣,只是改變這一點:

Thread.class_eval do 

要這樣:

Thread.class_exec(commentable) do |commentable| 

,它應該工作。

+0

實際上並不是真的 - 我的問題是關於在Thread類中創建新方法並在裏面使用可評論的內容 - 我不得不使用define方法在class_exec裏面 - 因爲def my_new_method裏面的contenxt發生了變化。 但它有助於class_exec,謝謝 – sandric 2013-05-14 16:52:40

+0

@sandric:很高興以某種方式幫助。 – Linuxios 2013-05-14 22:23:13

相關問題