我创建了两个定制的marshal_load
和marshal_dump
方法来排除一个无法编组的特定实例变量。我使用了this问题中的建议。
我现在正在尝试从文件中编写和读取编组对象。这是原始代码
class MarshalTest
include MarshalUtils
attr_reader :foo, :bar, :baz
def initialize(foo = nil, bar = nil, baz = nil)
@log = File.open('test.log', 'w' )
@foo = foo
@bar = bar
@baz = baz
@log.close
end
end
module MarshalUtils
def marshal_dump
instance_variables.reject{|m| m == :@log}.inject({}) do |vars, attr|
vars[attr] = instance_variable_get(attr)
vars
end
end
def marshal_load(vars)
vars.each do |attr, value|
instance_variable_set(attr, value) unless attr == :@log
end
end
end
模块MarshalUtils
创建并读取字符串。我如何转换它以便写入和读取二进制文件,因为我的对象非常大?这是我的尝试
module MarshalUtils2
def marshal_dump
dump = instance_variables.reject{|m| m == :@log}.inject({}) do |vars, attr|
vars[attr] = instance_variable_get(attr)
vars
end
File.open('dump.marshal', 'wb') do |f|
f.write(dump)
end
end
def marshal_load(vars)
vars.each do |attr, value|
instance_variable_set(attr, value) unless attr == :@log
end
end
end
File.write
是否实际创建了二进制文件?如果是,我该如何阅读并重新创建原始对象?