How to load vars from users' app.conf (quite long)

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 :slight_smile:

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:
[…]

I’d suggest using eval in this case. It seems quite correct to do so; just use
RE to ensure the correctness of the format so it can’t do any harm. If you
want to be sure, put it in a sandbox (a thread where $SAFE=6) during
evaluation. I’m not entirely sure if global variables are contained within
threads though.

Gavin

···

From: “gabriele renzi”

6: With a singleton instead of globals.

comment

var1=foo
var2=bar

comment

require ‘singleton’

module App
class Config
def initialize
@fields = {}
File.open(“app.conf”) do |f|
f.read.scan(/^(\w+)=(\w+)$/).each do |name, value|
@fields[name] = value
end
end
end

def [](name)
  @fields[name]
end

end

CONF = Config.instance
end

require ‘app/config’

p App::CONF[‘var1’]
p App::CONF[‘var2’]

You’ll probably want to improve the regex passed to #scan in
Config#initialize.

HTH

Massimiliano

···

On Sun, Sep 29, 2002 at 11:11:53PM +0900, gabriele renzi <surrender_it@ wrote:

1: clear, long, unpretty
2: shameless ripped from rbot/config.rb
3: shorter, but using eval
4: huge case , kind of
5: quicky and risky: