【发布时间】:2012-07-15 15:01:33
【问题描述】:
How do I remove leading whitespace chars from Ruby HEREDOC? 部分回答了这个问题
在 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
添加'begin'和'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 是要保留的最小空间,但我猜这不适用于制表符。或者让heredoc的第一行确定左边距,像这样:
puts <<-HEREDOC
FIRST_LINE
Real code here
HEREDOC
strip_heredoc 将删除“FIRST_LINE”,但它也会设置需要删除的空格/空白的数量。所以输出会在'Real code here'前面有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
【问题讨论】:
标签: ruby whitespace heredoc thor