Reputation: 49
I need to use render_to_string method outside the controller. So I create controller instance like:
controller = class_name.constantize.new # Rails controller instance
controller.params = params
controller.action_name = 'index'
controller.create_global_current_user user
index_render_options = controller.send('index_render_options')
controller.send('render_to_string', index_render_options)
But it fails because request object inside is nil. Could you help me with it? how to create fake request for controller object?
Upvotes: 0
Views: 2293
Reputation: 2157
Based on this blog post the env parameter looks like
env = {
'REQUEST_METHOD' => 'GET',
'PATH_INFO' => '/hello',
'HTTP_HOST' => 'skylight.io',
# ...
}
Since Rails does not allow an empty map as the env
parameter, the minimum code for creating a request object would be
request = ActionDispatch::Request.new({ "REQUEST_METHOD" => "GET" })
Upvotes: 0
Reputation: 49
SOLVED.
Added
controller.request = ActionDispatch::Request.new({})
resp = controller.class.make_response!(controller.request)
controller.set_response!(resp)
so now it looks like
controller = class_name.constantize.new
controller.params = params
controller.action_name = 'index'
controller.request = ActionDispatch::Request.new({})
resp = controller.class.make_response!(controller.request)
controller.set_response!(resp)
controller.create_global_current_user user
index_render_options = controller.send('index_render_options')
controller.send('render_to_string', index_render_options)
Upvotes: 0