0

在将单独的模块包含到单独的类中之后,我在使用实例方法扩展类时遇到了一些问题

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

现在我想这样称呼这个方法:

thread = Thread.new
thread.commentable

问题当然是没有与类 eval 的 include 方法绑定,我可以保存要传递到 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

但是正如我猜想的那样,这会为类的单音对象创建实例方法,因此我只能通过

Thread.commentable

再说一次,没有约束力...

4

1 回答 1

0

如果我理解正确,您需要能够访问扩展程序中的commentable变量,对吗?Thread

如果是这样,只需更改:

Thread.class_eval do

对此:

Thread.class_exec(commentable) do |commentable|

它应该工作。

于 2013-05-10T13:56:52.720 回答