views:

246

answers:

2

I want to load a data structure into a Ruby script which maps a string to a triple which contains some combination of regular expressions, scripts and atoms. The file that it loads from needs to be human writeable.

Currently I'm writing the file to contain a Ruby hash, loading that as a string and calling eval. Ie.

Data file

{ "key1" => [ /pattern/, "text", "text" ],
  "key2" => [ "text2", :nil, "text3" ],
  "key3" => [ "text4", /pattern2/, /pattern3/ ] }

Script

def get_mapping
  f = File.new path
  return eval(f.read())
end

This is fine and works, but feels (i) like a bit of a hack, (ii) unsafe. So I'm curious to know: is there a better way of doing this?

It's almost JSON but I don't think that can handle atoms or regular expressions easily. The file format can be changed as look as it remains reasonably human read/writeable.

+6  A: 

You should really be using YAML for this sort of stuff, your code is really risky.

YAML supports regexps and is fairly extensible.

Sam Saffron
Risk is mitigated by the environment it's used it for the most part, though yes, in general, I agree. YAML is almost ideal by the looks of it, just wish I didn't have to to "!ruby/regexp".
Ian G
+1  A: 

Hashes and Arrays can be marshalled. This might be helpful if you want to store data from your program in a file. If you are interested in giving user a chance to provide data in external file you can take a look at YAML.

samuil