Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 使用添加并一起初始化的方法获取无限循环_Ruby - Fatal编程技术网

Ruby 使用添加并一起初始化的方法获取无限循环

Ruby 使用添加并一起初始化的方法获取无限循环,ruby,Ruby,我想在对象的所有方法中钩住一些动作,但我的尝试似乎进入了一个无限循环 一旦我注释掉初始化,问题就解决了 我怎样才能解决这个问题 我用这种方式调用对象TaskRecord.new,然后像stack overflow class TaskRecord @@cnt = 0 #To add log when calls a method def self.method_added(name) if /hook/.match(name.to_s) or method_defin

我想在对象的所有方法中钩住一些动作,但我的尝试似乎进入了一个无限循环

一旦我注释掉
初始化
,问题就解决了

我怎样才能解决这个问题

我用这种方式调用对象
TaskRecord.new
,然后像
stack overflow

class TaskRecord
  @@cnt = 0
  #To add log when calls a method
  def self.method_added(name)    
    if /hook/.match(name.to_s) or method_defined?("#{name}_without_hook")
      return 
    end
    class_eval do 
      alias_method "#{name}_without_hook" , "#{name}"
      define_method name do
        p "#{name} called"
        send "#{name}_without_hook"
      end
    end
  end

  def initialize
    ...
  end

  def somemethods
    ...
  end

由于
initialize
是一个私有方法,请尝试以下操作:

class Test
   def initialize
   end
   alias_method :old_initialize, :intialize
end

Test.method_defined? 'initialize'     # returns false
Test.method_defined? 'old_initialize' # returns false too
您可以使用
private\u方法\u defined?

if /hook/.match(name.to_s) or
  method_defined?("#{name}_without_hook") or
  private_method_defined?("#{name}_without_hook")

你能展示一下你是如何调用导致无限循环的方法的吗?@ArupRakshit我更新了它