简体   繁体   English

如何在加载 Rails 环境的情况下调试单个文件

[英]How to debug single file with Rails environment loaded

I've been learning Ruby and now Rails.我一直在学习 Ruby 和现在的 Rails。

I know in VS Code you configure the debugger with the following config我知道在 VS Code 中你使用以下配置配置调试器

            {
                "name": "Debug Ruby",
                "type": "Ruby",
                "request": "launch",
                "cwd": "${workspaceRoot}",
                "program": "${file}",
            },

It works just like ruby xxx.rb and pauses at breakpoints.它的工作原理与ruby xxx.rb ,并在断点处暂停。

But I want to be able to do the same for any file in my rails project.但我希望能够对我的 Rails 项目中的任何文件执行相同的操作。 For example, I just wrote a model user.rb for my project and i want to test and debug some functions.I tried the following:例如,我刚刚为我的项目写了一个 model user.rb ,我想测试和调试一些功能。我尝试了以下方法:

            {
                "name": "Rails run",
                "type": "Ruby",
                "request": "launch",
                "cwd": "${workspaceRoot}",
                "program": "${workspaceRoot}/bin/rails",
                "args": [
                    "runner",
                    "${file}"
                ]
            },

but this wont stop at the breakpoints.但这不会在断点处停止。 there's also rails server option but that's for running the whole app but i just want to test&debug one single piece of code.还有rails server选项,但那是为了运行整个应用程序,但我只想测试和调试一段代码。

I think it doesnt work because rdebug doesnt attach to any subprocesses that the runner spins up to run the script.我认为它不起作用,因为 rdebug 没有附加到运行器启动以运行脚本的任何子进程。 You could try launching the debugger directly from the ruby file you want the runner to use.您可以尝试直接从您希望运行程序使用的 ruby 文件启动调试器。 You'd need to add an attach use-case in the debugger options:您需要在调试器选项中添加一个附加用例:

For example: .vscode/launch.json :例如: .vscode/launch.json

{
    "name" : "Attach to rdebug-ide",
    "type": "Ruby",
    "request": "attach",
    "cwd": "${workspaceRoot}",
    "remoteHost": "127.0.0.1",
    "remotePort": "1234",
    "remoteWorkspaceRoot": "${workspaceRoot}"
},

Than in xxx.rb add the following to the top of the file:比在xxx.rb文件的顶部添加以下内容:

require 'ruby-debug-ide'
require 'resource-struct'
options = ResourceStruct::FlexStruct.new({ 
    host: '127.0.0.1', 
    port: '1234' 
})

### Anything above this line will get run twice
Debugger.debug_program(options) unless Debugger.started?
### Rest of code you want to debug

Next run rails r xxx.rb it displays something like:接下来运行rails r xxx.rb它显示如下内容:

Fast Debugger (ruby-debug-ide 0.7.3, debase 0.2.4.1, file filtering is supported) listens on 127.0.0.1:1234

Lastly attached your debugger.最后附上你的调试器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM