gpt4 book ai didi

ruby-on-rails - 从生产 irb 调试方法

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

当我寻找问题时,例如针对特定的 ActiveRecord 对象,我经常发现自己在我的生产系统上执行以下操作:

# RAILS_ENV=production bundle exec

irb(main)> article = Article.find(123)
=> #<Article id: 123, title: "Foobar">
irb(main)> article.do_something(3)
NoMethodError: undefined method `id' for nil:NilClass

有时我无法重现,为什么 article.do_something(3) 行会抛出错误,所以我想直接在我的服务器上以生产模式进行调试。

现在的问题是:如何在对象/实例 article 上使用参数 3 进入方法 #do_something

当然,可以在该方法中设置一个断点,重新加载生产环境并让所有客户在该断点处等待,直到我完成调试...但这不是最好的主意。

So, is there a way to debug into a method of a specific instance from a running irb / pry session? (both would be ok)

最佳答案

在尝试和更多谷歌搜索之后,我想我找到了适合我的解决方案。

  1. 登录到您的 Rails 控制台/irb/pry session
  2. 设置您的案例(例如加载您的模型、需要依赖项...),以便您可以在一行中执行要调试的代码
  3. require 'byebug'(或 require 'debugger' 对于旧的 ruby​​ 版本)
  4. 现在是有趣的部分:将调试器语句放在要调试的行前面,如下所示 binding.pry; user.do_something调试器; user.do_something
  5. 现在您在调试器中。也许您必须使用 next 跳转到下一行(如果您启用了快捷方式,则只需使用 n )以进入您的方法。

这是我们生产系统中的一个完整示例:

[1] pry(main)> require 'byebug'
=> true
[2] pry(main)> user = User.find(2)
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
=> #<User id: 2, name="XXX XXX">
[3] pry(main)> user.full_name
NameError: undefined local variable or method address for #<User:0x0055b168663590>

[4] pry(main)> binding.pry; user.full_name

[68, 73] in /usr/src/app/app/models/user.rb
68: end
69:
70: def full_name
=> 71: "#{address.firstname} #{address.last_name}"
72: end
73: end
(byebug)

关于ruby-on-rails - 从生产 irb 调试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36747003/

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