gpt4 book ai didi

ruby-on-rails - 如何找到方法的 Rails 模块路径

转载 作者:行者123 更新时间:2023-12-05 03:02:41 25 4
gpt4 key购买 nike

ruby/rails 的新手。在大型 Rails 应用程序中,我遇到了一些方法,但找不到它们的文档。例如,有一个方法process。当我反省和检查它的祖先时,我可以找到 Rails::Controller::Testing::TemplateAssertions.process 但是谷歌搜索没有给我任何关于如何使用该方法的文档,只是method's definition这是非常模糊的。

我想找到的是 ActionDispatch::Integration::Session.process 然后我可以在 https://api.rubyonrails.org/ 中查找它并获得有关如何使用该方法的详细文档。我想我很难找到这个“原始”模块路径,因为 Rails 使用了 mixins。我找到它的唯一方法是在我发现它在某些评论中提到之前筛选 rails 存储库的文件和文件。所以我的问题是,是否有更确定性的方法来找到方法的起源?

编辑:这段代码的上下文看起来有点像这样:

require 'test_helper'
class C < ActionDispatch::IntegrationTest
include OtherHelper
...
process(argA,argB,argC)
end

最佳答案

有一些东西可以用来帮助自省(introspection)和调试:

  • 安装和要求 pry , pry-byebug并放置一个 binding.pry代码中的某处将允许您 step/next通过逻辑,直到你到达你认为你需要去的地方
  • 使用owner方法如对您的帖子的评论中所述。如果你有 User模型,例如,您可以从控制台类型 User.method(:_update_callbacks).owner并看到它来自 ActiveRecord::Base
  • 您可以使用 .source_location方法来查看在哪个文件中定义了某些内容。例如,从 Rails 控制台我可以键入 User.method(:_update_callbacks).source_location并看到该方法是在 active_support/callbacks.rb 的第 819 行定义的文件(在响应中注明完整路径)
  • 如果您知道该模块被包含在内,但无法弄清楚您还可以在本地系统上编辑 gem 以打印它被包含在何处

下面打印出Bar

module Foo
def self.included(base)
puts "including..."
puts base
puts "included..."
end
end

class Bar
include Foo
end

可能有更好/更清洁的东西,但这些可能有用。

根据我在下面的评论,关于使用 pry 的更多详细信息:

鉴于我已经运行了 gem install pry pry-byebug并具有以下代码示例:

require 'pry'
require 'pry-byebug'

module Foo
def blah
puts "in Foo"
end
end

class Bar
include Foo

def blah
binding.pry
super
puts "in Bar"
end
end

x = Bar.new
x.blah

当您点击 binding.pry , 在 super 之前,您可以调用next这将使您进入新文件,您可以在其中看到文件名和行号。您需要添加 binding.pry在您机器上的实际 gem 文件中。 bundle open <gemname>gem open <gemname>应该在您的编辑器中打开实际文件夹,只要您在 Gemfile 中配置了 pry/byebug(如果使用 bundler )或通过 gem 安装,它应该可以工作。

step with pry

关于ruby-on-rails - 如何找到方法的 Rails 模块路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54561270/

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