我需要将一个yaml文件加载到Hash中,
我该怎么办?
尝试使用YAML.load或Marshal.load生成损坏的对象反序列化一个非常简单的对象,因为在反序列化过程中不需要属于的类.
例:
# app/models/my_model.rb
class MyModel
attr_accessor :id
end
# test/unit/serializing_test.rb
require 'test_helper'
class SerializingTest < Test::Unit::TestCase
def test_yaml_serialize_structure
my_model = MyModel.new
my_model.id = 'my model'
File.open( "#{Rails.root}/tmp/object.yml" , 'w' ) do |f|
YAML::dump(my_model, f)
end
end
def test_yaml_deserialize_structure
object = YAML.load_file "#{Rails.root}/tmp/object.yml"
assert( object.instance_of? MyModel )
assert_equal( 'my model', object.id )
end
end
Run Code Online (Sandbox Code Playgroud)
使用此代码,我们可以运行此shell控制台会话而不会出现任何错误
$ ruby -Itest test/unit/serializing_test.rb -n test_yaml_serialize_structure
$ ruby -Itest test/unit/serializing_test.rb -n test_yaml_deserialize_structure
Run Code Online (Sandbox Code Playgroud)
但是如果我从Rails控制台运行反序列化调用,则对象不会被正确反序列化,因为该类永远不需要:
$ rails c
ruby-1.9.2-p0 …Run Code Online (Sandbox Code Playgroud)