gpt4 book ai didi

ruby-on-rails - 按名称记录调试日志中的每个方法调用

转载 作者:数据小太阳 更新时间:2023-10-29 08:09:50 26 4
gpt4 key购买 nike

我正在尝试调试一些不起作用的测试,但我遇到了一些问题。我在运行测试并将关键消息输出到日志时跟踪 test.log,但由于所有交织的回调和 Hook ,我不确定来自哪个模型的哪个方法正在调用哪个 SQL :)

我写了一些东西来记录一个方法名:

def log_mname
caller[0]=~/`(.*?)'/ # note the first quote is a backtick
Rails.logger.debug '=' * 80
Rails.logger.debug ">> #{Time.now} - #{$1}"
Rails.logger.debug '=' * 80
end

效果很好,但要求我将 log_mname 添加到模型中的每个方法,这是不现实的。我想要的是向我的 Rails 应用程序添加一个简单的行或 block ,让我基本上可以说“记录所有调用调试日志的方法。”

我尝试在模型的顶部使用 ruby​​ 的 set_trace_func 但它没有用。我也宁愿不必向每个模型添加一些东西,而是向 test/debug.rb 环境文件等添加一些东西。

有什么想法吗?

最佳答案

您所询问的概念称为反射;如果您有兴趣阅读更多相关信息。

为了回答你的问题,__method__ 在你想知道它的名称的方法中返回方法名称作为符号

$ irb
irb(main):001:0> def qwerty
irb(main):002:1> __method__
irb(main):003:1> end
=> nil
irb(main):004:0> qwerty
=> :qwerty
irb(main):005:0>

这适用于 Ruby 1.8.7

编辑

上面是打印方法名

为了动态显示方法调用,我会使用 ActiveSupport 的#constantize 风格与set_trace_func 显示调用跟踪。

# in your test environment initializer file
require 'active_support/inflector/inflections'
MODELS_TO_WATCH = Dir.entries("#{Rails.root}/app/models/").
gsub(".rb", ""). # strip all extensions from filenames
capitalize!. # no reason for the bang, just saving space
# constantize # make "User" string into User model, for e.g.
# if you constantize, remove `to_s` from `classname` in the proc below
# the version that worked for me was without constantizing but I figure both
# variations yield the same result

class_eval do |c| # Replace this with a "class DummyClass" for proper sandboxing
set_trace_func proc { |event, id, classname|
if event == "call" && MODELS_TO_WATCH.include?(classname.to_s)
puts "called #{classname}'s #{id}"
end
}
end

注意!set_trace_func 是一个leech 函数。它会锁定你的 Ruby 进程,直到进程被终止(许多 IRB 的死亡可以证明这一点)。我还没有找到撤消 set_trace_func 的方法。如果没有引入条件,它的打印结果很糟糕;这可能看起来像错误,但实际上不是。

这就是为什么我建议将其放入您的测试初始值设定项中的原因;并且很可能在一个虚拟类中!这样,当您在开发、生产或您设置的任何其他环境中重新启动 Rails 应用程序时,此 hack 不会影响它。

必须在类上下文中对 this 进行评估。我发现如果它是在实例上下文中计算的,因此 instance_eval,它会打印 Ruby 程序执行过程中发生的每个事件,除了被调用的函数。

关于ruby-on-rails - 按名称记录调试日志中的每个方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12901027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com