Hi gurus,
I’m writing a simple app that needs to read a configuration file in
the common unix format
#that is a comment
var_name=var
Well, the question is : what’s the better way to load those global
variables?
i thought 5 ways:
···
1: clear, long, unpretty
#I like adding methods to existing classes
class File
def read_val
readline.split("=")[1].sub("\n",’’)
end
end
file=File::new “app.conf”
$var1=file.read_val
$var2=file.read_val
…
$varN=file.read_val
file.close
(and what if the user leaves an empty line, or switches them ?)
2: shameless ripped from rbot/config.rb
IO.foreach(“app.conf”) do |line|
next if(line =~ /^\s*#/)
if(line =~ /(\S+)\s+=\s+(.*)$/)
$1 = $2 if($2)
end
3: shorter, but using eval
IO.foreach (“app.conf”) {|line| eval ("$#{line}") unless
line=~/(^#|^\s*$)/ }
(I supposed even the unless statement could be avoided, but I’m
getting a SyntaxError.
Anyway, I heard using eval is Wrong™, but what are the problems in
a use case like this?)
#these 2 ideas came out while I was writing this mesg:
4: huge case , kind of
case line
when line =~/varX=(.*)/
$varX=$1
…
end
(the user could reverse the order, delete some parameter,
adding useless ones and all should work anyway)
5: quicky and risky:
require “app.conf”
(I lose the tainted nature of input this way, actually I
should hope the user won’t load a var like rm -fr