Rails 2.3.14:如何序列化ActionController :: Request对象? [英] Rails 2.3.14: How to serialise an ActionController::Request object?

查看:74
本文介绍了Rails 2.3.14:如何序列化ActionController :: Request对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一些基于Rails 2.3.14控制器接收到的请求对象的方法来做事情.但是,我不想启动整个应用程序,甚至也不想启动控制器.我只想拥有一个可以在Rails环境之外使用的对象的编组副本.

I need to write some methods that Do Things based on the kind of request object received by a Rails 2.3.14 controller. However, I don't want to fire up the entire application, nor even a controller; I'd like to have just a marshalled copy of such an object that I can work with outside of the Rails environment.

不幸的是,传递给控制器​​的ActionController::Request对象在其深处包括Proc对象,这些对象本来就无法序列化.

Unfortunately, the ActionController::Request objects passed to controllers include, deep in their bowels, Proc objects which are inherently unserialisable.

有人知道序列化这些对象之一的方法,这样我就可以将其存储在数据文件中,然后在另一个脚本中重新创建它了吗?我宁愿不要猴子修补Proc类以提供#marshal_dump方法.

Does anyone know of a way to serialise one of these objects such that I can store it away in a data file and re-create it in another script? I would prefer not to monkey-patch the Proc class to provide a #marshal_dump method..

谢谢!

推荐答案

技巧是替换/删除不可序列化的对象(尤其是在env哈希中).我在此SO答案中实现了部分内容.我使用Rails 3.2.13 request对象略微更新了我的方法.

The trick is to replace/delete not serializable objects (especially in the env-hash). I implemented parts of it in this SO answer. I slightly updated my approach using a rails 3.2.13 request object.

##
# 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版本.


Update: owww, I've just seen that you are asking vor Rails 2.3.14. My visual filter let me see 3.2.14 instead. So this only works for a current rails version, sorry.

这篇关于Rails 2.3.14:如何序列化ActionController :: Request对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆