【问题标题】:How can I create a program to create multiple files from one template with different values inside?如何创建一个程序来从一个模板创建多个文件,其中包含不同的值?
【发布时间】:2010-05-28 07:54:29
【问题描述】:

我需要从一个模板创建 1500 多个 ruby​​ 文件,以进行一些我正在使用 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

我需要插入大量 URL - 每个文件中都插入一个,替换“$OLD_URL”和“$NEW_URL”。

有没有办法做这样的事情?

x = 0
而 (x {
打开模板.rb
查找 $CLASS_NAME 的所有实例并替换为 classnames.txt 中的 xxx
查找 $OLD_URL 的所有实例并替换为 listofurls.csv 中的 xxx
查找 $NEW_URL 的所有实例并替换为 listofurls.csv 中的 xxx
将文件另存为 ('redirect_' + 'x++')
x++
}

【问题讨论】:

    标签: ruby url redirect selenium


    【解决方案1】:

    正确的做法是使用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.
    ========================================
    

    【讨论】:

    • 这就是我所追求的,但我需要创建 1500 多个文件,每个文件中包含三个不同的变量。另外它需要从外部文件(csv)中读取值...
    • 使用CSV 库。这很简单。
    【解决方案2】:

    template.rb的内容读取为字符串,然后使用String#gsub在循环内编辑模板并保存修改后的模板。

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 1970-01-01
      • 2020-06-18
      • 2019-11-29
      • 2015-08-05
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多