【问题标题】:Indent multiline string in ERB在 ERB 中缩进多行字符串
【发布时间】:2013-06-29 15:47:31
【问题描述】:

我有一个来自外部库的字符串,如下所示:

s = "  things.each do |thing|\n    thing += 5\n    thing.save\n  end\n\n"

这个输入字符串不会改变。我需要使用 ERB 将其插入到文件中。例如:

erb = ERB.new("<%= s %>")
File.write("test.txt", erb.result(instance_eval('binding'))

我的问题是缩进。不对字符串做任何修改,文件会这样写:

  things.each do |thing|
    thing += 5
    thing.run
  end

注意缩进。然而,我想要做的是将文本均匀地插入另外两个空格,如下所示:

    things.each do |thing|
      thing += 5
      thing.run
    end

如果我这样做:

erb = ERB.new("  <%= s %>")

那么只有第一行会缩进。

    things.each do |thing|
    thing += 5
    thing.run
  end

可以通过修改初始字符串来实现..

erb = ERB.new("<%= s.gsub(/  (\w)/, "    \\1") %>")

.. 但这感觉有点乱。我真的不想在视图中这样做。有没有办法在 ERB 中缩进整个字符串,还是我不走运?我想我可能会。

【问题讨论】:

  • 你试过了吗? ERB.new("&lt;%= ' ' + s %&gt;")(这是一个 2 空格字符串被前置)。

标签: ruby string erb


【解决方案1】:

这是一个更简单(但扩展性较差)的替代解决方案:

def indent(str, amount)
  ' ' * amount + str.split("\n").join("\n" + ' ' * amount)
end

【讨论】:

  • 我在 erb 中使用了这段代码(减去方法定义),意在将多行代码字符串抽取到正确缩进的 YAML 变量中。
【解决方案2】:

我认为没有任何内置解决方案可以解决您的问题。但这并不意味着您不应该只构建自己的 :)

这样的事情应该可以工作:

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, "  ")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2011-03-22
    • 2011-01-31
    • 2021-01-01
    • 2016-07-27
    • 1970-01-01
    相关资源
    最近更新 更多