2010-05-28 51 views
0

我需要從一個模板中創建1500+個紅寶石文件,以進行一些測試,我正在使用Selenium進行測試。如何創建一個程序,以從一個模板中創建具有不同值的多個文件?

模板看起來是這樣的:

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_not be nil 

    puts "\n##### Success! #####\n\r" 

end # execute 

我有網址的我需要插入的負載 - 一個爲每個文件,替換「$ OLD_URL」和「$ NEW_URL」。

有沒有辦法做這樣的事情?

x = 0的
而(X < 1500)
{
開放template.rb
找到$ CLASS_NAME的所有實例和從classnames.txt
用xxx替換找到$ OLD_URL的所有實例與XXX代替從listofurls.csv
找到$ NEW_URL的所有實例,從listofurls.csv
用xxx替換文件另存爲( 'REDIRECT_' + 'X ++')
X ++
}

回答

0

正確的做法是使用ERB庫。

下面的代碼將根據預定義的模板生成兩個文件。

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 

template.erb樣子:

Title <%= file %> 
<%= "=" * 40 %> 
<%= contents %> 
<%= "=" * 40 %> 

這裏是aneqdote.txt內容:

Title anecdote 
======================================== 
There are 10 types of people in the world. 
======================================== 
+0

這之後幾乎我什麼,但我需要創建1500+文件有三個每個文件中有不同的變量。另外它需要從外部文件(csv)讀取值... – Jem 2010-05-28 12:13:27

+0

使用'CSV'庫。這非常直截了當。 – Yossi 2010-05-29 18:39:30

0

閱讀的template.rb內容爲一個字符串,然後使用String#gsub編輯循環內的模板並保存修改的模板。

相關問題