2010-09-10 86 views
4

我想在Ruby heredoc中迭代一個數組。heredoc裏面的Ruby語法?

<<-BLOCK 
Feature: User logs in 
    In order to post content 
    As an user 
    I want to log in 

<< Here i want to iterate scenarios >> 
BLOCK 

「場景」是我想要循環的數組。對於每一個元素我想打印出來:

Scenario: #{scenario} 
    Given 
    When 
    Then 

因此,舉例來說,如果「場景」載:

scenarios[0] = "User successfully logs in" 
scenarios[1] = "User failed to log in" 

我想定界符字符串是:

<<-BLOCK 
Feature: #{feature} 
    In order to #{in_order_to} 
    As #{as} 
    I want #{i_want} 

Scenario: User successfully logs in 
    Given 
    When 
    And 

Scenarios: User failed to log in 
    Given 
    When 
    And 
BLOCK 

我如何在Ruby heredoc裏面迭代?

回答

9

可以做,但我不知道它是最可讀的方式:

 
s = <<-BLOCK 
Feature: User logs in 
    In order to post content 
    As an user 
    I want to log in 

#{scenarios.map{|x| 
<<-INNERBLOCK 
Scenario: #{x} 
    Given 
    When 
    Then 
INNERBLOCK 
}} 

BLOCK 
+0

爲什麼它打敗了heredocs的目的?能夠在heredocs中擁有動態數據不行嗎? – 2010-09-10 20:30:04

+0

Btw。這不起作用\ n被解釋爲文本而不是新行。 – 2010-09-10 20:33:03

+0

奇怪。我仍然有\ n。以下是腳本和文件的樣子:http://pastie.org/1150945 – 2010-09-10 20:56:52

13

你可以使用ERB。這將是清潔並不算多更多的代碼:

require 'erb' 
s = ERB.new(<<-BLOCK).result(binding) 
Feature: User logs in 
    In order to post content 
    As an user 
    I want to log in 

<% scenarios.map do |x| %> 
    Scenario: <%= x %> 
    Given 
    When 
    Then 
<% end %> 
BLOCK 

第一行可能看起來怪異,所以我會打破它

s = ERB.new(<<-BLOCK).result(binding) 

ERB.new創建與傳遞的字符串作爲一個新的ERB模板其內容。 <<-BLOCK是一個heredoc,它表示接下來的heredoc值並將其分解到表達式中。 result(binding)評估當前上下文中的模板(binding是當前評估的上下文)。

從那裏你可以很容易地提取你的模板文件,因爲他們變得更大。

More about Ruby's heredocs by James Edward Gray II

+0

這是一個更好的解決方案,恕我直言 – rampion 2010-09-12 02:30:39