【问题标题】:Some hook after initialization of ruby class?ruby 类初始化后的一些钩子?
【发布时间】:2019-12-12 18:00:11
【问题描述】:

例如,我有一些具有此初始化的类:

class SomeClass < ActiveRecord
  call_some_method('bla_bla_bla')
  def some_method
    return 1
  end
  # end of initialization or definition(not really sure, sorry)
  # and here I want to call some code which can be added in other place of project
end

我想用我自己的代码添加钩子,它可以在初始化后添加或调用类的方法。我没有能力将一些代码直接添加到类定义中,这里我的意思不是关于类实例的初始化。
有没有办法做到这一点?

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

ActiveRecord 具有 after_initialize and after_find 挂钩,您可以在记录初始化(通过新建或构建)或加载(通过查找)后运行代码。

你可以使用类似的东西:

class SomeClass
  after_initialize :do_my_setup

  def do_my_setup
    # Your code here
  end
end

在新记录被实例化后,这会monkeypatch SomeClass 来运行你的设置方法。您可以使用它来为 ActiveRecord 对象的 instances 修补新方法,但这会对 Ruby 方法缓存产生一些影响,如果可以避免它,通常被认为是个坏主意。

如果您只需要向 SomeClass 类添加新方法 - 实例或类 - 您可以通过标准 Ruby 类扩展机制对其进行猴子补丁。

【讨论】:

    猜你喜欢
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 2012-08-22
    • 1970-01-01
    相关资源
    最近更新 更多