开发者

Ruby custom class to and from YAML;

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

  1. How do I achieve my goal? What methods should I use, between parsing, loading files or documents, to succe开发者_运维技巧ssfully 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.
  2. 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?


When you write to yaml, you don't need to first call to_yaml, just pass the object itself to YAML.dump( object )

This probably led you into other problems because the output of to_yaml was a string.. and the YAML.dump actually wrote your object as a string to to the file (that's why you have an initial "-- |" line. Anything code loading that file would load that data as a string.

Load a single object like this:

File.open( 'test_set.yaml', 'r') { |fh|  mq_loaded = YAML.load( fh ) }

The "new" you're using is generally confusing because new is a keyword.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜