2011-11-10 80 views
1

我知道我們可以做這樣的事情:可以在一個here文件中放置一個條件語句嗎?

puts <<START 
----Some documents 
#{if true 
"yesyesyesyesyesyesyesyesyesyes" 
else 
"nonononononononononononononono" 
end} 
----Some documents 
START 

但是,它可以這樣做:

puts <<START 
----Some documents 
#{if true} 
yesyesyesyesyesyesyesyesyesyes 
#{else} 
nonononononononononononononono 
#{end} 
----Some documents 
START 

爲什麼我想這是因爲我在這裏文檔中討厭的單/雙引號,避免他們會使文件更清晰

任何人都可以提供幫助嗎?

謝謝!

回答

2

也許你真的想使用ERB如果目的是執行模板。該局將支持分裂的if/else罰款:

require 'erb' 

template = ERB.new <<-DOC 
----Some documents 
<% if true %> 
yesyesyesyesyesyesyesyesyesyes 
<% else %> 
nonononononononononononononono 
<% end %> 
----Some documents 
DOC 

string = template.result(binding) 
+0

謝謝,它有幫助!特別是對於大一到紅寶石來說。 – aaron

0

你可以使用ERB如果你真的想這樣的事情:

str = <<-ERB 
----Some documents 
<% if true %> 
yesyesyesyesyesyesyesyesyesyes 
<% else %> 
nonononononononononononononono 
<% end %> 
----Some documents 
ERB 
erb = ERB.new(str, nil, '<>'); 
puts erb.result(binding) 
1

你可以考慮嵌套here文檔:

puts <<EOF 
---- Some documents 
#{if true; <<WHENTRUE 
yesyesyes 
WHENTRUE 
else <<WHENFALSE 
nonono 
WHENFALSE 
end 
}---- Some documents 
EOF 

請注意,您需要將關閉}上線的開始,或者你將有一個多餘的空行。

編輯:你可能避免,也許通過使用小助手功能得到更好一點的語法:

def if_text(condition, whentrue, whenfalse) 
    (condition ? whentrue : whenfalse).chomp 
end 

puts <<EOF 
---- Some documents 
#{if_text(true, <<ELSE, <<ENDIF) 
yesyesyes 
ELSE 
nonono 
ENDIF 
} 
---- Some documents 
EOF 
1

我給替代我贊成,這是用here文檔分配給變量,然後插在主定界符,因爲它得到了定界符的條件之外,從而給你正在尋找更好的透明度(尤其是當事情開始變得比一個人爲的例子更復雜):

cond = if true 
<<TRUE 
yesyesyesyesyesyesyesyesyesyes 
TRUE 
else 
<<NOTTRUE 
nonononononononononononononono 
NOTTRUE 
end.strip 

puts <<START 
----Some documents 
#{cond} 
----Some documents 
START 

如果你正在尋找一個模板,那麼這裏有很多,並且在我看來比ERB好很多(從看Haml開始)。

+0

謝謝,我會看看Haml – aaron

相關問題