How can I create a program to create multiple files from one template with different values inside?
I need to create 1500+ ruby files from a template for some testing I'm doing with Selenium.
The template looks like this:
class $CLASS_NAME
require "spec"
attr_accessor :title
include Spec::Example::ExampleGroupMethods
include Spec::Matchers
def initialize
@title = "$OLD_URL -> $NEW_URL"
end
def execute(selenium)
selenium.open "$OLD_URL"
sleep 1
puts 'Opening...'
sleep 1
url = selenium.get_location
puts 'Grabbing location...'
sleep 1
puts 'The URL is ' + url
puts 'Doing match...'
sleep 1
/$NEW_URL/.match(url).should_no开发者_如何学运维t be nil
puts "\n##### Success! #####\n\r"
end # execute
I have a load of URL's I need to insert - one into each file, replacing '$OLD_URL' and '$NEW_URL'.
Is there anyway to do something like this?
x = 0
while (x < 1500) { open template.rb find all instances of $CLASS_NAME and replace with xxx from classnames.txt find all instances of $OLD_URL and replace with xxx from listofurls.csv find all instances of $NEW_URL and replace with xxx from listofurls.csv save file as ('redirect_' + 'x++') x++ }
The proper way to do it is using the ERB
library.
The code below will generate two files according to predefined template.
require "erb"
File.open("template.erb") do |io|
template = ERB.new io.read
files = {:anecdote => "There are 10 types of people in the world.",
:story => "Once upon a time..."}
files.each do |file, contents|
File.open "#{file}.txt", "w" do |out|
out.puts template.result binding
end
end
end
When template.erb
looks like:
Title <%= file %>
<%= "=" * 40 %>
<%= contents %>
<%= "=" * 40 %>
Here is the contents of aneqdote.txt
:
Title anecdote
========================================
There are 10 types of people in the world.
========================================
Read the contents of template.rb
to a string, then use String#gsub to edit the template inside the loop and save the modified template.
精彩评论