如何在Rails控制台中以文本形式打印控制器?

问题描述

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

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

可以在某处查看它吗?我可以将其打印到Rails控制台上进行查看吗?

解决方法

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,: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 together和IO.readlines Method#source_location。但是恕我直言,这似乎是在浪费时间

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...