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! (eg @_action_name
, @_env
, etv... are already set!).
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. I've used caller
in a few places to understand how actions get called but haven't found the code I'm looking for.
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.
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.
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
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.