2013-05-10 72 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

相关问题