问题描述
我有一个来自外部库的字符串,如下所示:
I have a string from an external library that looks like this:
s = " things.each do |thing|\n thing += 5\n thing.save\n end\n\n"
此输入字符串将不会更改。我需要使用ERB将其插入文件中。例如:
This input string isn't going to change. I need to insert it into a file using ERB. e.g.:
erb = ERB.new("<%= s %>")
File.write("test.txt", erb.result(instance_eval('binding'))
我的问题是在不对字符串进行任何更改的情况下,文件将像这样编写:
My problem is the indentation. Without making any changes to the string, the file will be written like this:
things.each do |thing|
thing += 5
thing.run
end
注意但是,我想做的是在文本中均匀地再缩进两个空格,就像这样:
Note the indentation. What I want to do, however, is to insert the text uniformly indented another two spaces in, like so:
things.each do |thing|
thing += 5
thing.run
end
如果我这样做:
erb = ERB.new(" <%= s %>")
然后仅缩进第一行。
things.each do |thing|
thing += 5
thing.run
end
我可以通过mod实现
erb = ERB.new("<%= s.gsub(/ (\w)/, " \\1") %>")
..但这感觉有点乱。我真的不想在视图中这样做。有没有办法在ERB中缩进整个字符串,还是我不走运?
.. but that feels a bit messy. I don't really want to do that in the view. Is there a way to indent the entire string in ERB, or am I out of luck? I think I might be.
推荐答案
我认为您的问题没有内置的解决方案。但这并不意味着您不应该只构建自己的:)
I don't think that there is any builtin solution for your problem. But this does not mean you shouldn't just build your own :)
类似的东西应该可以工作:
Something like this should work:
class CodeIndenter < Struct.new(:code, :indentation)
def self.indent(*args)
self.new(*args).indent
end
def separator
"\n"
end
def indent
code.split(separator).map do |line|
indentation + line
end.join(separator)
end
end
s = " things.each do |thing|\n thing += 5\n thing.save\n end\n\n"
puts CodeIndenter.indent(s, " ")
这篇关于在ERB中缩进多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!