【问题标题】:How to print a controller as text in the rails console?如何在 Rails 控制台中将控制器打印为文本?
【发布时间】:2020-12-09 00:12:11
【问题描述】:

我想查看Devise::RegistrationsController(出于好奇,我将继承它,如图所示here

我尝试了明显的rails c 然后puts Devise::RegistrationsController 和一些变体(例如.to_s)但没有运气..

是否可以在某个地方查看,我可以将其打印到 rails 控制台查看吗?

【问题讨论】:

  • 您可以在devise gem 存储库中查看。例如github.com/heartcombo/devise/blob/master/app/controllers/devise/…
  • @dbugger 随机问题。代码是否可以在 Rails 应用程序中以某种方式搜索(和可编辑),还是只能在 github 上查看?
  • 据我所知。如果可以的话,我也不认为你会想要编辑它,它是非常可定制的,而 ruby​​ 让你可以修补那些不容易定制的东西。查看用于自定义控制器、视图等的设计存储库。我们有大约五种设计变体,所有这些都只是通过自定义各种位来完成。
  • 你也可以使用bundle open devise在编辑器中打开它

标签: ruby-on-rails devise rails-console


【解决方案1】:

Pry 是 IRB 的替代控制台,内置了源代码浏览。

安装pry-rails gem 并使用rails c 启动控制台,它将启动Pry 而不是IRB。

然后您可以使用show-source 直接从控制台查看gem 的源代码:

max@pop-os ~/p/sandbox> rails c
Running via Spring preloader in process 29286
Loading development environment (Rails 6.0.2.1)
[1] pry(main)> show-source Devise::RegistrationsController

From: /home/linuxbrew/.linuxbrew/lib/ruby/gems/2.7.0/gems/devise-4.7.2/app/controllers/devise/registrations_controller.rb @ line 3:
Class name: Devise::RegistrationsController
Number of monkeypatches: 4. Use the `-a` option to display all available monkeypatches
Number of lines: 166

class Devise::RegistrationsController < DeviseController
  prepend_before_action :require_no_authentication, only: [:new, :create, :cancel]
  prepend_before_action :authenticate_scope!, only: [:edit, :update, :destroy]
  prepend_before_action :set_minimum_password_length, only: [:new, :edit]

  # GET /resource/sign_up
  def new
    build_resource
    yield resource if block_given?
    respond_with resource
  end

  # POST /resource
  def create
    build_resource(sign_up_params)

    resource.save
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      set_minimum_password_length
      respond_with resource
    end
  end
:

如果您不想依赖 Pry 并坚持使用 IRB,您可以使用 cobble something togetherMethod#source_location 和 IO.readlines。但是恕我直言,这似乎是在浪费时间

【讨论】:

    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 2015-10-28
    • 2011-11-25
    • 2010-10-28
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    相关资源
    最近更新 更多