對這一問題的How do I remove leading whitespace chars from Ruby HEREDOC?如何刪除導致從一個Ruby定界符空白,而維修器材2個前導空格
部分回答了在Rails 3有一個方法#strip_heredoc
,即去掉所有的空格。 但是,在現有文件中插入行時,該文件已具有身份識別功能,但這種功能無法正常工作。一個例子:
begin
insert_into_file "#{app_name}/config/environments/production.rb", <<-DEVISE_MAILER_STUFF.strip_heredoc, :before => "end\n"
# for devise
config.action_mailer.default_url_options = { :protocol => 'https', :host => 'YOURHOSTNAME' }
config.action_mailer.delivery_method = :smtp
something.each do |x|
do stuff
end
DEVISE_MAILER_STUFF
end
在「開始」和「end」只添加到表明該源代碼有縮進。 heredoc在'#for devise'之前有4個空格。 @strip_heredoc將刪除所有這些空格,但它將在'do stuff'行中保留兩個額外的空格。
在environments/production.rb
這將是這樣的:
MyApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# *** Identation here is two spaces! (We are in a block.) ***
# for devise
config.action_mailer.default_url_options = { :protocol => 'https', :host => 'YOURHOSTNAME' }
config.action_mailer.delivery_method = :smtp
something.each do |x|
do stuff
end
# back to original identation of this file
end # MyApp::Application.configure block!
如何解決這個問題? 也許有其他方法而不是heredoc? 我想也許strip_heredoc(min)
其中min
是保留空間的最小值,但是這並不適用於我猜的標籤。或有定界符的第一行確定的左邊空白處,這樣的:
puts <<-HEREDOC
FIRST_LINE
Real code here
HEREDOC
這FIRST_LINE'將通過strip_heredoc
被刪除,但它也將設置的空間/空格需要被刪除的號碼。所以輸出將在'真實代碼'前面有2個空格。
更新:也許是這樣的:
String.class_eval do
def strip_heredoc_with_indent(indent=0)
new_indent = (self.empty? ? 0 : (scan(/^[ \t]*(?=\S)/).min.size - indent))
gsub(/^[ \t]{#{new_indent}}/, '')
end
end
可能重複http://stackoverflow.com/questions/3772864/how-do-i-remove-leading-whitespace-chars-from -ruby-heredoc) – 2014-01-03 17:01:21