I am making a few ruby scripts to write an nginx configuration file.
I have two files: one is a template with a few placeholders and the second stores a serialised hash with all information I need.
The information consists of a generic name of an application, an url, the number of ports to be used and the first port.
I'll make a short example to make it clear. This is my template:
Template file:
upstream thin {
{upstream}
}
server {
listen 80;
server_name .{url};
root /var/www/{name};
}
This is, more or less, how the information is stored in the second file with a ruby code:
Ruby script that saves the info:
apps = Hash.new { |h, k| h[k] = Hash.new }
apps["foo"] = {"url" => "foo.co.uk", "ports" => 3, "first" => 3000 }
apps["bar"] = {"url" => "bar.com", "ports" => 2, "first" => 3003 }
serialisedApps = Marshal.dump(apps)
File.open('/home/deploy/data/apps', 'w') {|f| f.write(serialisedApps) }
Now I can load this information like this:
apps = Marshal.load File.read('/home/deploy/data/apps')
And I can iterate through my hashes and print the ports for foo (3000, 3001 and 3002) and bar (3003 and 3004).
apps.each {|key, value|
pn = value["ports"]
fp = value["first"]
pn.times do |i|
currPort = fp + i
puts "#{key} in port #{currPort}"
end
}
Now, I need to get that template and replicate 2 files (for 'foo' and 'bar') like so:
upstream thin {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
server 127.0.0.1:3002;
}
server {
listen 80;
server_name .foo.co.uk;
root /var/www/foo;
}
Now I just need to load the template, replace the placeholders and save it elsewhere. I managed to do that with a bash script, but I want to avoid it and use only ruby. Is there a simple way of doing that?
Thanks in advance!
Look into using using ERB. http://ruby-doc.org/stdlib-1.9.3/libdoc/erb/rdoc/ERB.html
It's built into Ruby's standard library, and does exactly what you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.