【问题标题】:Ruby method which is running after method is defined定义方法后运行的 Ruby 方法
【发布时间】:2016-11-23 09:57:56
【问题描述】:

假设我有一个class Alex

class AB < Alex
  some_definition_here # it changes some class variables
end

我的问题是:对于仅在定义类后执行的类,是否有类似 self.included 的东西?我只想在更改某些类变量后才能访问类变量。

【问题讨论】:

  • “像 self.included 这样的任何东西”的名称是“对象生命周期挂钩”。

标签: ruby class oop


【解决方案1】:

是的,有。但这有点棘手,因为 ruby​​ 中的开放类概念没有“类定义”的概念。

您正在寻找的是TracePoint。可能的用法:

  TracePoint.new(:end) do |tp|
    if tp.self.name == 'AB'
      # DO SOME STUFF
      # at this very moment class was closed with end for the 1st time
      tp.disable
    end
  end.enable

【讨论】:

    猜你喜欢
    • 2021-11-16
    • 2016-01-08
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多