[英]Define instance method of a class after class already defined in 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
現在,我想像這樣調用此方法:
thread = Thread.new
thread.commentable
問題是,當然,沒有與類eval的include方法綁定的東西,我可以將要傳遞到變量的變量保存在ActsAsCommentable模塊中,但我不想這樣做。 有沒有更好的辦法?
我試着做
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
再說一次,沒有約束力...
如果我對您的理解正確,那么您需要能夠訪問Thread
擴展中的commentable
變量,對嗎?
如果是這樣,只需更改以下內容:
Thread.class_eval do
對此:
Thread.class_exec(commentable) do |commentable|
它應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.