我正在使用 Web 服务并使用 Savon 执行 +-1000 个(付费)请求并将请求解析为 csv 文件。 如果解析失败,我会将 xml.hash 响应保存在文件中。 如何初始化保存到文件中的哈希值? (或者我应该保存在 XML 中,然后让 savon 再次将其变成哈希值?
额外信息:
client = Savon.client do
wsdl "url"
end
response = client.call(:read_request) do
message "dat:number" => number
end
我使用response.hash来构建/解析我的csv数据。例如:
name = response.hash[:description][:name]
如果构建失败,我正在考虑将response.hash保存到文件中。但问题是我不知道如何重用保存的响应(XML/哈希),以便可以使用保存的响应运行更新版本的构建/解析。
最佳答案
您想要将哈希序列化为文件,然后再次将其反序列化。
您可以使用YAML以文本形式完成此操作或JSON并以二进制形式通过 Marshal 。
编码(marshal)
def serialize_marshal filepath, object
File.open( filepath, "wb" ) {|f| Marshal.dump object, f }
end
def deserialize_marshal filepath
File.open( filepath, "rb") {|f| Marshal.load(f)}
end
编码数据有一个主要版本号和次要版本号,因此如果编码数据版本发生更改,则不能保证始终在另一个 Ruby 中加载。
YAML
require 'yaml'
def serialize_yaml filepath, object
File.open( filepath, "w" ) {|f| YAML.dump object, f }
end
def deserialize_yaml filepath
File.open( filepath, "r") {|f| YAML.load(f) }
end
JSON
require 'json'
def serialize_json filepath, object
File.open( filepath, "w" ) {|f| JSON.dump object, f }
end
def deserialize_json filepath
File.open( filepath, "r") {|f| JSON.load(f)}
end
有趣的是,YAML 很慢,Marshal 和 JSON 很快。
关于Ruby 从文件构建哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24702824/