Safe hash loading in Ruby

I want to load a data structure into a Ruby script that maps a string to a triple that contains some combination of regular expressions, scripts, and atoms. The file from which it is loaded must be written by a person.

I am currently writing a file to contain a hash of a Ruby file, loading it as a string and calling eval. Those..

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 works fine and works, but feels (i) like a little hacking, (ii) unsafe. So I'm curious to know: is there a better way to do this?

It's almost JSON, but I don't think it can easily handle atoms or regular expressions. The file format can be changed since it remains reasonably accessible for reading / writing.

+3
2

YAML , .

YAML .

+5

Hash es Array . , . , YAML.

+1

Source: https://habr.com/ru/post/1718011/


All Articles