–
No matter how far down the wrong road you’ve gone, turn back. -
Turkish Proverb
On 21-Jun-2006, at 23:04, Victor ‘Zverok’ Shepelev wrote:
require ‘nezbit’
Sorry, but I can’t understand the example 
What is ‘Nezbit’ ? How it all works?
V.
Maybe this will be easier to understand:
#!/usr/bin/env ruby
require ‘yaml’
require ‘pp’
This class will save and load Hash objects using a made-up file
format.
It is for an example of transforming YAML to another format.
class MyFormat
Dump a Hash object to a file.
def MyFormat.dump(obj, file)
fail “This example only handles Hashes” if ! obj.is_a?(Hash)
obj.each_pair { |key, value|
MyFormat.dump(value, file) if value.is_a?(Hash)
file << "<#{key}>\n"
value.each { |val|
file << "\t<#{val}>\n"
}
}
end
A regular expression to match keys and values of the form:
…
…
KEY_VALUE_RE = /
<(.+?)> (?# A key name surrounded by < > . )
\n (?# Key names are followed by a newline. )
( (?# Begin capturing. )
(?: (?# Begin a group. )
\t (?# Values have a tab character in front of
them. )
<.+?> (?# The value is surrounded by < > . )
\n (?# Values are followed by a newline. )
) (?# End the group. )
+ (?# There should be one or more values. )
) (?# End capturing. )
/xm # x means this is an extended regexp.
# m means it will match across multiple lines.
Process the contents of filename, and return a Hash
object with the key and value pairs.
def MyFormat.load_file(filename)
obj = {}
File.open(filename) { |file|
lines = file.read
lines.scan(KEY_VALUE_RE) { |key, values|
# Keys are symbols
key = key.to_sym
# Extract the values, removing extraneous characters.
vals = values.split(/\n/)
vals.collect! { |val|
val.gsub!(/^[\t<]+/, ‘’)
val.gsub!(/>$/, ‘’)
}
if vals.size == 1
obj[key] = vals[0]
else
obj[key] = vals
end
}
}
return obj
end
end
Files to play with.
YAML_FILENAME = Dir.pwd + ‘/tree.yaml’
MYFORMAT_FILENAME = Dir.pwd + ‘/tree.myformat’
A sample object to dump and load back.
tree = { :name => ‘ruby’,
:uses => [ ‘scripting’, ‘web’, ‘etc’ ]
}
Save the tree object to a file using YAML.
File.open(YAML_FILENAME, ‘w’) { |file|
YAML.dump(tree, file)
}
Now we can transform the YAML file into a MyFormat file.
File.open(MYFORMAT_FILENAME, ‘w’) { |file|
a_tree = YAML.load_file(YAML_FILENAME)
MyFormat.dump(a_tree, file)
}
Now get the object from the MyFormat file.
tree2 = MyFormat.load_file(MYFORMAT_FILENAME)
Show the original and the transformed objects.
pp tree
pp tree2