繁体   English   中英

当猴子在gem中修补单个方法时,我可以使它知道我的应用程序中的活动记录吗?

[英]When monkey-patching a single method in a gem can I make it aware of an active record in my app?

我正在寻找对Monkey-patch https://stackoverflow.com/a/21446021的答案。

在此示例中,gem(其他人的库)具有方法someMethod(),该方法最终将调用我修补的方法。

我的应用看起来像这样

activeRecord = ... # gets an ActiveRecord object that I want to update 
options = {..}
@gem_object = SomeLibrary::Class.new(options)

@gem_object.someMethod()

现在someMethod()最终将调用修补的方法。 我想让修补方法知道activeRecord,以便它可以对其进行更新。 我想知道是否可以避免在调用someMethod()时将activeRecord作为参数添加到堆栈跟踪中的所有方法。

我将其存储在一个普通的类中

class StoreRecord
  def self.activeRecord
    @active_record
  end
  def self.activeRecord=(record)
    @active_record = record
  end
end

所以你的代码变成

StoreRecord.activeRecord = ... # gets an ActiveRecord object that I want to update 
options = {..}
@gem_object = SomeLibrary::Class.new(options)

@gem_object.someMethod()

并且您可以通过修补方法访问StoreRecord.activeRecord

暂无
暂无

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

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