0

我需要在控制器外部使用 render_to_string 方法。所以我创建控制器实例,如:

  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)

但它失败了,因为里面的请求对象是零。你能帮我吗?如何为控制器对象创建虚假请求?

4

2 回答 2

0

解决了。

添加

  controller.request = ActionDispatch::Request.new({})
  resp = controller.class.make_response!(controller.request)
  controller.set_response!(resp)

所以现在看起来

      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)
于 2020-01-13T22:45:40.483 回答
0

基于this blog post,env参数看起来像

env = {
  'REQUEST_METHOD' => 'GET',
  'PATH_INFO' => '/hello',
  'HTTP_HOST' => 'skylight.io',
  # ...
}

由于 Rails 不允许空映射作为env参数,因此创建请求对象的最少代码是

request = ActionDispatch::Request.new({ "REQUEST_METHOD" => "GET" })
于 2021-09-02T12:49:22.170 回答