相关疑难解决方法(0)

33
推荐指数
4
解决办法
4万
查看次数

Rails不会在反序列化YAML/Marshal对象时加载类

  • Rails:3.0.3
  • Ruby:1.9.2

尝试使用YAML.loadMarshal.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)

ruby-on-rails classloader deserialization

11
推荐指数
1
解决办法
4459
查看次数