如何找到一种方法Rails的模块路径

问题描述 投票:1回答:1

新来的Ruby / Rails。在一个大的Rails应用程序,我碰到过的方法并不能为他们找到的文档。例如,有一种方法process。当我反思,并检查它的祖先,我可以得到Rails::Controller::Testing::TemplateAssertions.process但谷歌搜索,不给我说说如何使用方法,只是这是很不起眼的method's definition任何文件。

我想找到的是ActionDispatch::Integration::Session.process,我可以再看看在https://api.rubyonrails.org/并获得如何使用方法详细的文档。我想我已经很难找到,因为对Rails的使用混入的这种“原始”模块路径。我发现的唯一途径是通过导轨库的文件和文件筛选之前,我发现它在一些评论中提及。所以我的问题是,有没有找到一种方法的起源更确定的方式?

编辑:该代码的背景下看起来有点像这样:

require 'test_helper'
class C < ActionDispatch::IntegrationTest
   include OtherHelper
   ...
   process(argA,argB,argC)
end
ruby-on-rails ruby introspection
1个回答
2
投票

还有,你可以用它来帮助反省和调试有两件事情:

  • 安装和要求prypry-byebug并在代码放置binding.pry地方可以让你step / next通的逻辑,直到你得到的地方,你认为你需要
  • 使用owner方法,在您的文章评论说。如果你有一个User模型,你可以,例如,从一个控制台类型User.method(:_update_callbacks).owner,看到它从ActiveRecord::Base
  • 您可以使用.source_location方法,看看哪一些文件中定义。例如,从铁轨控制台我可以输入User.method(:_update_callbacks).source_location,看到方法在active_support/callbacks.rb文件的819行定义(在响应指出的完整路径)
  • 如果你知道这是被包含在模块,但它被列入其中,没能找出你也可以在本地系统上编辑宝石打印

下面的打印出Bar

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

class Bar
  include Foo
end

很可能有更好的东西/吸尘器在那里,但这些可能是有用的。

使用撬,每低于我的评论的更多细节:

既然我已经运行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.prysuper之前,你可以调用next,这将逐步指导您到新文件中,你可以看到文件名和行号。你将需要添加binding.pry在实际的宝石文件你的机器上。 bundle open <gemname>gem open <gemname>应该在你的编辑器中打开的实际文件夹,只要你有撬/ byebug在你的Gemfile配置(如果使用捆绑),或通过gem安装,它应该工作。

step with pry

© www.soinside.com 2019 - 2024. All rights reserved.