Ruby custom class to and from YAML;
Posted
by Sanarothe
on Stack Overflow
See other posts from Stack Overflow
or by Sanarothe
Published on 2010-06-07T23:58:47Z
Indexed on
2010/06/08
0:02 UTC
Read the original article
Hit count: 371
Hi. I'm having trouble deserializing a ruby class that I wrote to YAML.
Where I want to be
I want to be able to pass one object around as a full 'question' which includes the question text, some possible answers (For multi. choice) and the correct answer. One module (The encoder) takes input, builds a 'question' class out of it and appends it to the question pool. Another module reads a question pool and builds an array of 'question' objects.
Where I am currently
Sample Question Pool
--- |
--- !ruby/object:MultiQ
a: "no"
answer: "no"
b: "no"
c: "no"
d: "no"
text: "yes?"
Encoder dump to YAML file. Object is a MultiQ filled up with input. (See below.)
def dump(file, object)
File.open(file, 'a') do |out|
YAML.dump(object.to_yaml, out)
end
object = nil
end
MultiQ Class definition
class MultiQ
attr_accessor :text, :answer, :a, :b, :c, :d
def initialize(text, answer, a, b, c, d)
@text = text
@answer = answer
@a = a
@b = b
@c = c
@d = d
end
end
The decoder (I've been trying different things, so what's here wasn't my first or best guess. But I'm at a loss and the documentation doesn't really explain things thoroughly enough.)
File.open( "test_set.yaml" ) do |yf|
YAML.load_documents( yf ) { |item|
new = YAML.object_maker( MultiQ, item)
puts new
}
end
Questions you can answer
- How do I achieve my goal? What methods should I use, between parsing, loading files or documents, to successfully deserialize a Ruby class? I've already looked over the YAML Rdoc, and I didn't absorb very much, so please don't just link me to it.
- What other methods would you suggest using? Is there a better way to store questions like this? Should I be using document db, relational db, xml? Some other format?
© Stack Overflow or respective owner