简体   繁体   English

如何手动运行Rails控制器动作(“离线”)?

[英]How can I run a Rails controller action manually (“offline”)?

I need a way to run controller actions manually "offline" and store the result output. 我需要一种手动“离线”运行控制器操作并存储结果输出的方法。

Looking into controller initialization, it seems nothing interesting happens there. 查看控制器初始化,似乎没有什么有趣的事情发生。

Looking into send_action , it seems by the time this is called, the controller instance already knows much about the action! 查看send_action ,似乎在调用此方法时,控制器实例已经对该动作了如指掌! (eg @_action_name , @_env , etv... are already set!). (如@_action_name@_env ,ETV ...已经设置!)。

I need to understand where that happened so I can do in manually to a controller instance. 我需要了解发生的位置,以便可以手动对控制器实例进行操作。 I have never quite figured out how to navigate code as dynamic as Rails, and cannot seem to find out where this set up occurs. 我从来没有想过如何像Rails一样动态地导航代码,而且似乎也找不到这种设置的发生位置。 I've used caller in a few places to understand how actions get called but haven't found the code I'm looking for. 我在一些地方使用了caller ,以了解如何调用操作,但没有找到我要查找的代码。

Any help is appreciated. 任何帮助表示赞赏。

I suppose by running offline you mean, run it via code in the rails console, or some sort of lib or model. 我想通过脱机运行是指通过Rails控制台中的代码或某种类型的lib或模型运行它。

You can access a controller information using the following command: 您可以使用以下命令访问控制器信息:

ActionDispatch::Integration::Session.new(Rails.application)

This will create a new session (similar to integration tests session), where you can perform requests to the rails application. 这将创建一个新会话(类似于集成测试会话),您可以在其中执行对Rails应用程序的请求。

You perform a request to your action/controller in the following manner: 您可以通过以下方式向操作/控制器执行请求:

session.get(path)

To capture the ouput, you can use the value store in session.response and if you want to get the body, you can use: session.response.body 要捕获输出,可以在session.response使用值存储,如果要获取正文,可以使用: session.response.body

Example: 例:

Let's say you have the following controller: 假设您有以下控制器:

# app/controllers/tests_controller.rb

class TestsController < ApplicationController
  layout false
  def index
    @name = 'Test'
  end
end

and the following view: 和以下视图:

# app/views/tests/index.html.erb

Hi <%= @name %>

the following routes: 以下路线:

# config/routes.rb
...
resources :tests, only: :index
...

you can create the following file: 您可以创建以下文件:

# run.rb
session = ActionDispatch::Integration::Session.new(Rails.application)
path = Rails.application.routes.url_helpers.tests_path
session.get(path)
puts session.response.body

and run it via: rails runner run.rb , you should get 'Test' 并通过以下方式运行它: rails runner run.rb ,您应该获得“测试”

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

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