Home How can I run a Rails controller action manually ("offline")?
Reply: 1

How can I run a Rails controller action manually ("offline")?

z5h
1#
z5h Published in 2018-01-10 19:43:06Z

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! (e.g. @_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.

Jonathan Duarte
2#
Jonathan Duarte Reply to 2018-01-11 11:42:31Z

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'

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.400015 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO