【问题标题】:Rails 2.3.14: How to serialise an ActionController::Request object?Rails 2.3.14:如何序列化 ActionController::Request 对象?
【发布时间】:2011-11-28 01:59:48
【问题描述】:

我需要编写一些基于 Rails 2.3.14 控制器接收到的请求对象类型的方法。但是,我不想启动整个应用程序,甚至也不想启动控制器;我想要一个这样的对象的编组副本,我可以在 Rails 环境之外使用它。

不幸的是,传递给控制器​​的ActionController::Request 对象在其内部深处包括本质上不可序列化的Proc 对象。

有谁知道序列化其中一个对象的方法,以便我可以将其存储在数据文件中并在另一个脚本中重新创建它?我不希望对 Proc 类进行猴子修补以提供 #marshal_dump 方法..

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby serialization marshalling


    【解决方案1】:

    诀窍是替换/删除不可序列化的对象(尤其是在 env-hash 中)。我在this SO answer 中实现了其中的一部分。我使用 rails 3.2.13 request 对象稍微更新了我的方法。

    ##
    # build a serializable hash out of the given request object
    def make_request_serializable(request)
      request_hash = {
        :env => request.env.clone,
        :filtered_parameters => request.filtered_parameters.clone,
        :fullpath => request.fullpath,
        :method => request.method,
        :request_method => request.request_method
      }
      #clean up the env-hash, as it contains not serializable objects
      request_hash[:env].tap do |env|
        env.delete "action_dispatch.routes"
        env.delete "action_dispatch.logger"
        env.delete "action_controller.instance"
        env.delete "rack.errors"
        env["action_dispatch.remote_ip"] = env["action_dispatch.remote_ip"].to_s 
      end
      request_hash
    end
    
    # later in the controller
    puts make_request_serializable(request).to_json
    #=> {"env":{"SERVER_SOFTWARE":"thin 1.5.1 codename Straight Razor","SERVER_NAME":"localhost","rack.input":[],"rack.version":[1,0], ... (shortened, as it's a lot of output)
    

    更新:噢,我刚刚看到你在询问 vor Rails 2.3.14。我的视觉过滤器让我看到3.2.14。所以这只适用于当前的 rails 版本,抱歉。

    【讨论】:

    猜你喜欢
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 2014-10-17
    • 2012-01-28
    • 2012-06-30
    相关资源
    最近更新 更多