Flash Rails 3-将HTTP状态更改为200,并将状态添加到响应主体

Flash Rails 3-将HTTP状态更改为200,并将状态添加到响应主体,flash,ruby-on-rails-3,Flash,Ruby On Rails 3,我需要捕获HTTP响应,就像它离开rails一样,并重写如下: 创建一个根状态节点,其中包含状态代码,然后 将标题状态重写为200 例如,对于所有响应,将其状态设置为根节点,然后重写其标题: HTTP/1.1 404 Not Found Content-Type:text/html This page was not found 为此: HTTP/1.1 200 OK Content-Type: text/html <status='404'> This page was no

我需要捕获HTTP响应,就像它离开rails一样,并重写如下:

  • 创建一个根状态节点,其中包含状态代码,然后
  • 将标题状态重写为200
  • 例如,对于所有响应,将其状态设置为根节点,然后重写其标题:

    HTTP/1.1 404 Not Found
    Content-Type:text/html
    
    This page was not found
    
    为此:

    HTTP/1.1 200 OK
    Content-Type: text/html
    
    <status='404'>
    This page was not found
    </status>
    
    HTTP/1.1200正常
    内容类型:text/html
    找不到此页
    
    背景: 将Rails 3与Flash客户端一起使用


    由于浏览器的限制,HTTP 200以外的任何内容都不能保证传递到客户端。有些允许201次通过,但不是全部。此外,大多数情况下,只有主体能够通过,任何标题都会被剥离。

    我会使用机架中间件,因为处理标题和重写主体非常容易。 将其放入
    app/middleware/flashfix.rb

        class FlashFix
          def initialize(app)
            @app = app
          end
    
          def call(env)
            status, headers, response = @app.call(env)
            if status == 404 
              [200, headers, "<status='404'>" + response.body + "</status>"]
            else
              [status, headers, response]      
            end
          end
        end
    
    中间件就位后,您所需要做的就是告诉Rails使用它

        class Application < Rails::Application
          config.middleware.use "FlashFix"          
        end 
    
    类应用程序

    如果您不熟悉Rack,我建议您使用Rack中间件,因为处理标头和重写正文非常容易。 将其放入
    app/middleware/flashfix.rb

        class FlashFix
          def initialize(app)
            @app = app
          end
    
          def call(env)
            status, headers, response = @app.call(env)
            if status == 404 
              [200, headers, "<status='404'>" + response.body + "</status>"]
            else
              [status, headers, response]      
            end
          end
        end
    
    中间件就位后,您所需要做的就是告诉Rails使用它

        class Application < Rails::Application
          config.middleware.use "FlashFix"          
        end 
    
    类应用程序

    如果您不熟悉Rack,我建议您

    我已经尝试过您所写的内容,但无法使用。有时
    响应
    对象是一个
    数组
    ,有时是一个
    动作调度::响应
    ,无论哪种情况,我都无法使用它。我还尝试过重写状态:
    status,headers,response=@app.call(env)
    [200,headers,response]
    …但这也不起作用。我需要使用另一种方法来加载模块,所以这可能是问题的一部分。在rails树中,我应该将您给出的文件示例放在哪里?例如/lib/rack/flash\u fix.rb?我试过你写的东西,但没法用。有时
    响应
    对象是一个
    数组
    ,有时是一个
    动作调度::响应
    ,无论哪种情况,我都无法使用它。我还尝试过重写状态:
    status,headers,response=@app.call(env)
    [200,headers,response]
    …但这也不起作用。我需要使用另一种方法来加载模块,所以这可能是问题的一部分。在rails树中,我应该将您给出的文件示例放在哪里?例如/lib/rack/flash\u fix.rb?