1

I want to replace properties in one file from those in another. (I am new to ruby, and read about Ruby and YAML. I have a Java background)

Eg.

File 1

server_ip_address=$[ip]
value_threshold=$[threshold]
system_name=$[sys_name]

File 2

ip=192.168.1.1
threshold=10
sys_name=foo

The ruby script should replace the $ values by their real values (I do not know if $[] is the format used in ruby. Also do Files 1 and 2 have to be YAML files, or erb files?) and produce File 1 as :

server_ip_address=192.168.1.1
value_threshold=10
system_name=foo

I searched the web for this, but could not express it in the right keywords to find a solution/pointer to a solution/reference material on google. How can this be done by a ruby script?

Thanks

3
  • Is this an arbitrary template format you've invented, or is it something you've inherited? In ERB this is done with <%= ip %> as an example. In YAML you'd define variables like ip: 192.168.1.1. Commented Feb 20, 2013 at 7:55
  • As I said in my question, "I do not know if $[] is the format used in ruby. Also do Files 1 and 2 have to be YAML files, or erb files?" Commented Feb 20, 2013 at 8:00
  • They don't have to be anything, but it would be easier if file 1 was ERB and file 2 was YAML. That you didn't know if it was used in Ruby wasn't an explanation as to where this came from. Commented Feb 20, 2013 at 8:06

1 Answer 1

1

If you can switch the formats, this should be as easy as:

require 'yaml'

variables = YAML.load(File.open('file2.yaml'))
template = File.read('file1.conf')

puts template.gsub(/\$\[(\w+)\]/) { variables[$1] }

Your template can stay as-is, but the substitution file would look like:

ip: 192.168.1.1
threshold: 10
sys_name: foo

This makes it easy to read in using the YAML library.

Sign up to request clarification or add additional context in comments.

3 Comments

Your script before you made an edit gave the following error /.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/erb.rb:838:in `eval': wrong argument type Array (expected Binding) (TypeError) from /.rvm/rubies/ruby-1.9.3-p385/lib/ruby/1.9.1/erb.rb:838:in `result' from abcd.rb:5:in `<main>' Here abcd.rb is the file into which I put the ruby script
Can you please post the earlier (without the edit) script (after correcting it), since i'd like to use the erb format.
The down-side to the ERB format, and why I removed it, was due to how you need to have local variables defined. This is considerably more awkward than simply referencing a Hash. The ERB documentation shows several examples. Creating arbitrary local variables from a YAML file is a recipe for trouble later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.