ruby - How to exclude an instance variable from marshal dump -
my object contains instance variable point file object amongst several other attributes. because of marshal cannot serialize it. how can write bespoke dump method exclude instance variable?
class area attr_accessor :area attr_reader :several_other_attributes ........ def initialize(name) @area = name @several_other_attributes = .... @log = file.open( 'test.log', 'w') end end
you can write marshal_dump , marshal_load method marshals specified number of instance variables. here's generic example of do:
class marshaltest attr_reader :foo, :bar, :baz, :t unmarshaled_variables = [:@foo, :@bar] def initialize(foo = nil, bar = nil, baz = nil, t = nil) @foo = foo @bar = bar @baz = baz @t = t end def marshal_dump instance_variables.reject{|m| unmarshaled_variables.include? m}.inject({}) |vars, attr| vars[attr] = instance_variable_get(attr) vars end end def marshal_load(vars) vars.each |attr, value| instance_variable_set(attr, value) unless unmarshaled_variables.include?(attr) end end end example usage:
1.9.3-p550 :026 > m = marshaltest.new(1, 2, 3, 4) => #<marshaltest:0x007ff73194cae8 @foo=1, @bar=2, @baz=3, @t=4> 1.9.3-p550 :027 > m.foo => 1 1.9.3-p550 :028 > m.bar => 2 1.9.3-p550 :029 > m.baz => 3 1.9.3-p550 :030 > m.t => 4 1.9.3-p550 :031 > s = marshal.dump(m) => "\x04\bu:\x10marshaltest{\a:\t@bazi\b:\a@ti\t" 1.9.3-p550 :032 > n = marshal.load(s) => #<marshaltest:0x007ff73112b828 @baz=3, @t=4> 1.9.3-p550 :033 > n.foo => nil 1.9.3-p550 :034 > n.bar => nil 1.9.3-p550 :035 > n.baz => 3 1.9.3-p550 :036 > n.t => 4 as can see, instance variables foo , bar ignored in marshaling/unmarshaling.
Comments
Post a Comment