简体   繁体   English

在已经在ruby中定义了类之后,定义类的实例方法

[英]Define instance method of a class after class already defined in ruby

I have some problem with extending class with instance method after separate module is included into separate class 在将单独的模块包含到单独的类中之后,我无法使用实例方法扩展类

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

And now I want to call this method somelike this: 现在,我想像这样调用此方法:

thread = Thread.new
thread.commentable

The problem is, of course is that there is no binding with include method for class eval, and I could save variables that I want to pass into class eval in ActsAsCommentable module, but I dont want to. 问题是,当然,没有与类eval的include方法绑定的东西,我可以将要传递到变量的变量保存在ActsAsCommentable模块中,但我不想这样做。 Is there a better way? 有没有更好的办法?

I tried to do instead 我试着做

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

But As I guessed this creates instance method for singletone object of class and therefore I can call it only through 但是正如我猜想的那样,这为类的单调对象创建了实例方法,因此我只能通过

Thread.commentable

And again, no binding... 再说一次,没有约束力...

If I understand you correctly, you need to be able to access the commentable variable inside your Thread extension, right? 如果我对您的理解正确,那么您需要能够访问Thread扩展中的commentable变量,对吗?

If so, just change this: 如果是这样,只需更改以下内容:

Thread.class_eval do

To this: 对此:

Thread.class_exec(commentable) do |commentable|

And it should work. 它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM