方法_添加红宝石的堆栈级别太深

时间:2018-11-26 18:46:37

标签: ruby module hook

我创建了一个模块来在类中的方法调用之前挂接方法:

module Hooks

def self.included(base)
 base.send :extend, ClassMethods
end


module ClassMethods
  # everytime we add a method to the class we check if we must redifine it
  def method_added(method)
    if @hooker_before.present? && @methods_to_hook_before.include?(method)
      hooked_method = instance_method(@hooker_before)
      @methods_to_hook_before.each do |method_name|
        begin
          method_to_hook = instance_method(method_name)
        rescue NameError => e
          return
        end
        define_method(method_name) do |*args, &block|
          hooked_method.bind(self).call
          method_to_hook.bind(self).(*args, &block) ## your old code in the method of the class
        end
      end
     end
   end

  def before(*methods_to_hooks, hookers)
   @methods_to_hook_before = methods_to_hooks
   @hooker_before = hookers[:call]
  end
 end
end

我已经将该模块包含在我的一个课程中:

require_relative 'hooks'

class Block
  include Indentation
  include Hooks
  attr_accessor :file, :indent
  before :generate, call: :indent
  # after  :generate, call: :write_end

  def initialize(file, indent=nil)
    self.file = file
    self.indent = indent
  end

  def generate
    yield
  end
end

此Block类是另一个类的父类,该类正在实现自己的版本的generate方法,并且该类实际上已实现。

当我的代码运行时,在某种无限循环中实际上使用method:generate作为参数来调用method_added。我不知道为什么method_added被困在这个无限循环中。您知道这段代码有什么问题吗? 这是完整代码的链接: link to code on github

1 个答案:

答案 0 :(得分:6)

由于在define_method内调用method_added,导致了无限递归。堆栈跟踪(不幸的是您没有提供)应该显示此内容。

解决此问题的一个稍微丑陋的解决方法是明确设置变量(例如@_adding_a_method)并将其用作method_added的保护子句:

module ClassMethods
  def method_added(method)
    return if @_adding_a_method

    if @hooker_before.present? && @methods_to_hook_before.include?(method)
      # ...

      @_adding_a_method = true
      define_method(method_name) do |*args, &block|
        # ...
      end
      @_adding_a_method = false

      # ...
    end
  end
end

但是,退后一步,我不确定该模块要实现什么。您不能仅通过Module#prepend而不是通过元编程来实现这一点吗?

这段代码使我想起了您在旧的Ruby 1.8 / 1.9教程中可以找到的有关高级元编程技术的内容; Module#prepend使得这种解决方法在大多数情况下都是多余的。