Question : How to trigger commands in ruby read from an external file?

This is purely a self learning exercise, I'm not sure whether this is going to be possible or not, though I'm sure it would allow for some great flexibility in future code.

What I want, is to load a txt file in, and execute it line by line as if it were ruby code, for example, instead of this:

#Note: This script from Gertone, from my last question.
def method1(var1, var2, var3, var4)
  puts var1
  puts var2
  puts var3
  puts var4
ed

inFile = File.open("variables.txt", "r")
vars = {}
inFile.readlines().each do |line|
  line.scan(/^(\S+)\s*=\s*(\S+).*$/) do |key,val|
    vars[key] = val
     end
  end
inFile.close
method1(vars["var1"],vars["var2"],v]ars["var3"],vars["var4"])
#End ruby script

Which outputs:
value1
value2
value3
value4

I'd like to do the same thing, but instead of just reading the variable from the text file using a regex, to execute the text file as if it were a ruby script, i.e. if the text file was:

#begin txt file
var1 = value1
var2 = value2
var3 = value3
var4 = value4
puts var1
puts var2
puts var3
puts var4
#end txt file

For the ruby script to load the text file then execute it.

Is this possible in a scalable manner?

As a note, this is the way I attempted it so far, which I didn't expect to work.. it met expectations:

#Begin Ruby Script
def runFile(mFileName)
  inFile = File.new(mFileName, "r")
  inFileC = inFile.readlines(rFileName)
  inFile.close
  return inFIleC
end

commands = runFile(input.txt)
commands.each do |i|
  i
end
#End Ruby Script

Answer : How to trigger commands in ruby read from an external file?

Well you can not expect that anything  you write in  a file can be seen as ruby expression.
But $VAR1 = "value" should do
Howerver I do not feel your approach is a good one. I can not see what you win with it.
but here we go:
content of t1.txt:

$VAR1 = "var1"

content if use_t1_txt.rb
inFile = File.open("t1.txt", "r")
vars = []
inFile.readlines().each do |line|
  eval line
end

print("VAR1 = #{$VAR1}\n")

output:
 ruby use_t1_txt.rb
VAR1 = var1

However it seems you want to use e.g yaml really.
http://ruby.lickert.net/yaml/index.html

Regards
Friedrich

Random Solutions  
 
programming4us programming4us