I would prefer to write objects into separate files but your way of serialization is also ok.
Here is the solution for your case;
RUBY_OBJECT = '--- !ruby/object:'
def load_objects(file_content)
object_contents = file_content.split(RUBY_OBJECT)
object_contents.map do |object_content|
YAML.load(RUBY_OBJECT + object_content)
end.compact
end
##########
File.open 'test.yml', 'r+' do |f|
f.write YAML.dump(a)
f.write YAML.dump(b)
f.seek(0)
file_content = f.read
c, d = *load_objects(file_content)
puts c
puts d
end
You can also run regex against the file content to get individual object definitions.
If using one file for serialization is a strict requirement, you could serialize an array of objects to the file like so;
require 'yaml'
class A
attr_accessor :num
def initialize(num)
@num = num
end
end
a = A.new(1)
b = A.new(2)
File.open('test.yml', 'w+') do |f|
f.write YAML.dump([a, b])
end
objects = YAML.load_file('test.yml')