James G. wrote:
On Jun 5, 2006, at 7:38 AM, Shane E. wrote:
Question, should {w: 1, t: 7} be an OpenStruct or remain a hash?
My opinion is an OpenStruct, for consistency.
James Edward G. II
Great, then here is my solution along with test code and input file. Not
as small as most solutions, but hopefully understandable. Please let me
know if you spot anything wrong with it.
— yaml2os.rb —
#!/usr/local/bin/ruby -w
require ‘yaml’
require ‘ostruct’
class YAML2OS
attr_reader :os
def initialize( file = nil )
convert(file) if file
end
def convert( file )
yaml = YAML.load(File.open(file))
@os = hash2os(yaml)
end
private
Check for hashes and arrays inside ‘hash’. Convert any hashes.
def hash2os( hash )
hash.each_key do |key|
hash[key] = hash2os(hash[key]) if hash[key].is_a?(Hash)
chk_array(hash[key]) if hash[key].is_a?(Array)
end
hash = OpenStruct.new(hash)
end
Check for hashes and arrays inside ‘array’. Convert any hashes.
def chk_array( array )
array.each_index do |i|
array[i] = hash2os(array[i]) if array[i].is_a?(Hash)
chk_array(array[i]) if array[i].is_a?(Array)
end
end
end
— tc_yaml2os.rb —
#!/usr/local/bin/ruby -w
require ‘test/unit’
require ‘ostruct’
require ‘yaml2os’
class TC_YAML2OS < Test::Unit::TestCase
def setup
@os = OpenStruct.new
@os.foo = 1
@os.bar = OpenStruct.new
@os.bar.baz = [ 1, 2, OpenStruct.new({‘b’ => 1, ‘c’ => 2}),
[3, 4, [5, OpenStruct.new({‘d’ => 3})]] ]
@os.bar.quux = 42
@os.bar.doctors = [ ‘William Hartnell’, ‘Patrick Troughton’,
‘Jon Pertwee’, ‘Tom Baker’, ‘Peter Davison’,
‘Colin Baker’, ‘Sylvester McCoy’, ‘Paul
McGann’,
‘Christopher Eccleston’, ‘David Tennant’,
OpenStruct.new({‘w’ => 1, ‘t’ => 7}) ]
@os.bar.a = OpenStruct.new({‘x’ => 1, ‘y’ => 2, ‘z’ => 3})
@os.bar.b = OpenStruct.new({‘a’ => [ 1,
OpenStruct.new({‘b’ =>
2}) ]})
test_construction
end
def test_construction
@yaml2os = YAML2OS.new(‘test.yaml’)
assert_not_nil(@yaml2os)
assert_instance_of(YAML2OS, @yaml2os)
assert_equal(@os, @yaml2os.os)
@yaml2os = YAML2OS.new
assert_not_nil(@yaml2os)
assert_instance_of(YAML2OS, @yaml2os)
assert_nil(@yaml2os.os)
end
def test_convert
os = @yaml2os.convert(‘test.yaml’)
assert_equal(@os, os)
assert_equal(@os, @yaml2os.os)
end
end
— test.yaml —
foo: 1
bar:
baz: [1, 2, {b: 1, c: 2}, [3, 4, [5, {d: 3}]]]
quux: 42
doctors:
- William Hartnell
- Patrick Troughton
- Jon Pertwee
- Tom Baker
- Peter Davison
- Colin Baker
- Sylvester McCoy
- Paul McGann
- Christopher Eccleston
- David Tennant
- {w: 1, t: 7}
a: {x: 1, y: 2, z: 3}
b: {a: [1, {b: 2}]}