Ruby on rails 在ruby实例中调用proc时,它的stac级别会太深

Ruby on rails 在ruby实例中调用proc时,它的stac级别会太深,ruby-on-rails,ruby,proc,Ruby On Rails,Ruby,Proc,今天我遇到了一个关于ruby的非常有趣的问题。我有一个模块/轨道问题: module BreakCacheModule extend ActiveSupport::Concern module ClassMethods def breakable_cache_for(method_name, &block) method_name = method_name.to_sym set_breakable_cache_proc(method

今天我遇到了一个关于ruby的非常有趣的问题。我有一个模块/轨道问题:

module BreakCacheModule
  extend ActiveSupport::Concern      

  module ClassMethods
    def breakable_cache_for(method_name, &block)
      method_name = method_name.to_sym
      set_breakable_cache_proc(method_name, block)
      define_breakable_cache_method(method_name)
    end

    def define_breakable_cache_method(method_name) 
      instance_eval(
        "def #{method_name}
          # here will be Rails.cache.fetch block around line below once I figure out this problem
          @_break_cache_procs[#{method_name}].call  # !!! this line will cause an issue
        end"
      )
    end

    def set_breakable_cache_proc(method_name, block)
      @_break_cache_procs ||={}
      @_break_cache_procs.merge!({method_name => block})
      @_break_cache_procs
    end
  end

end
在我的模型中

class Client < ActiveRecord::Base
  include BreakCacheModule

  breakable_cache_for :all_client_ids do
    Client.pluck :id
  end
end
但当我这样做的时候:

Client.instance_variable_get("@_break_cache_procs")[:all_client_ids].call
#=> [1,2,3]
功能完全相同,唯一的区别是我不是从instance_eval调用proc

我错过了什么吗

我的ruby-2.0.0-p247和Rails 3.2.14

谢谢你的帮助


接受后更新

总而言之,我实际上从两个地方得到了这个错误:

    "def #{method_name}
      Rails.cache.fetch(#{method_name.to_s}) do     # method_name should be in quotes
        @_break_cache_procs[#{method_name}].call    # missing colon ...look on answer 
      end
    end"
所以代码应该是这样的

  instance_eval(
    "def #{method_name}
      Rails.cache.fetch('#{method_name.to_s}') do
        @_break_cache_procs[:#{method_name}].call
      end
    end"
  )

传递给
instance\u eval
的字符串实际上是:

"def all_client_ids
  @_break_cache_procs[all_client_ids].call
end"
您可能已经注意到问题:缺少一个冒号

这应该是正确的代码:

def define_breakable_cache_method(method_name) 
  instance_eval(
    "def #{method_name}
      # here will be Rails.cache.fetch block around line below once I figure out this problem
      @_break_cache_procs[:#{method_name}].call  # !!! this line will cause an issue
    end"
  )
end

嗨,是的,那只是我的输入错误,但不管有没有冒号,结果都是一样的
SystemStackError:stack level太深了
…thx真的吗?要调试这个问题,我认为您可以打印出传递给
instance\u eval
的字符串。这样更容易发现问题。AAAAAA!我是个白痴,是的,你们是对的,这是因为结肠。它不起作用,因为之前我尝试它时,实际上从
Rails.cache.fetch method\u name
中得到了相同的错误(我传递方法\u name时没有将其包装为撇号)
def define_breakable_cache_method(method_name) 
  instance_eval(
    "def #{method_name}
      # here will be Rails.cache.fetch block around line below once I figure out this problem
      @_break_cache_procs[:#{method_name}].call  # !!! this line will cause an issue
    end"
  )
end