I found a lot of documentation that told me how to put an object into a YAML file. In my particular case I am reading through a file that needs to create or update a lot of things. I show the user what’s about to happen and give them 1 last chance to back out.
I store each set of changes/additions in an object, and it works great. You have something that is nice and legible, too.
The problem is that retrieving the info from the YAML file was proving difficult for me.
I did what this documentation told me to do, and I got an error. After much googling and cursing, I found this post that said they also had trouble and gave up because XML is easier.
F that.
So I got it to work, and here’s what I did…I started simple:
#!/usr/local/bin/ruby
require 'yaml'
class Bling
attr_accessor :aaa, :bbb
def initialize(a, b)
self.aaa = a
self.bbb = b
end
end
fling = Bling.new("a", "b")
floo = Bling.new(1, 2)
# write (marshal) the object(s) to a file
File.open("object.yml", "w") do |f|
f.puts fling.to_yaml
f.puts floo.to_yaml
end
# read the object(s) back
File.open( 'object.yml' ) do |yf|
YAML.load_documents( yf ) do |ydoc|
## ydoc contains the single object from the YAML document
puts "#{ydoc.aaa} #{ydoc.bbb}"
end
end
Bam!
Turns out the key for me was making the attributes accessible (attraccessor). When you read the object back from the file it recreates them (Object.new anyone)?
I was struggling because I could see the attributes when I inspected the object as I read through the file. I could also get to them when I did Object.ivars‘attribute’, but this didn’t work on the production host. It worked great on my box, which made me crazy.
The other gotcha for me was that I needed to require the class file in the method that was recreating the objects.
Now my app is happy.