From: Bill Guindon Date: 2005-03-07T16:49:43+09:00 Subject: Re: YAML to objects - how? On Mon, 7 Mar 2005 07:46:42 +0900, Joel VanderWerf wrote: > Bill Guindon wrote: > > Do I need the colons before the field names? I'm not doing that now. > > Oh, not at all. I just did that because I tend to use symbols rather > than strings when I am describing attr_accessors and the like. But you > can use strings for better readability in the yaml file. > > > I'll give that a shot, was wondering if there was a way to auto create > > objects from the YAML load, but yeah, I could loop through them and do > > it that way. I'll see how it goes. > > If you want to autocreate, you can use the syntax for defining the class > of objects, but the YAML file will look messier. You can see how it will > look by creating some objects in ruby code, and them calling #to_yaml on > them. F'rexample: > > require 'yaml' > > class C > attr_accessor :x > end > > c = C.new > c.x = {:foo => ["bar"] } > > puts c.to_yaml > > The output is > > --- !ruby/object:C > x: > :foo: > - bar > > If you YAML.load this, it will create an instance of C. > > Alternately maybe there is some hook in the YAML parser that lets you > say "instantiate all hashes with objects of class C", but that seems > problematic if you use hashes elsewhere in the data. > > Another option is to extend the YAML parser to recognize some custom > types that have less cumbersome syntax than "!ruby/object:YourClass". > You can find examples in yaml/types.rb in your ruby lib dir. I ended up going with your first suggestion (after getting a slightly firmer grasp of YAML). The alternatives seem to carry too high a price for "auto" object creation. In the long term, I hope that changes, in the short term, looping through what I have will work fine. Thx for you input. -- Bill Guindon (aka aGorilla)