在Ruby中为动态变量创建占位符标记

时间:2017-01-15 21:41:34

标签: ruby-on-rails ruby

我正在寻找一种方法来定义一组占位符/合并标记或实现DSL,其中视图文件中使用的一组模板标记将动态替换条件变量值。

例如,模板可能如下所示:

The quick <<COLOR>> <<ANIMAL_1>> jumps over the lazy <<ANIMAL_2>>

当然输出导致:

The quick brown fox jumps over the lazy dog

这超出了使用&lt;%= animal.color%&gt;在ERB模板中。在这种情况下,理想情况下,用户应该能够在表单输入中使用这些标记,并使用与数据库中其余文本一起保存的标记别名。

我不确定如何引用这些标签,所以这里是Mandrill文档中关于他们自己的“合并标签”功能的示例:How to Use Merge Tags to Add Dynamic Content

有没有可以做到这一点的现有宝石?如果没有,我怎么能实现类似的东西?

2 个答案:

答案 0 :(得分:3)

这是以前answer的改编版本。给定String和Hash,expand方法只与sub迭代,直到找不到占位符。

class String
  def has_placeholder?
    self=~/<<\w+>>/
  end
end

wordbook = {
  "<<COLOR>>"=> "brown",
  "<<ANIMAL_1>>"=> "fox",
  "<<ANIMAL_2>>"=> "dog"
}

def expand(sentence, wordbook)
  while sentence.has_placeholder? do
    sentence.sub!(/(<<\w+>>)/){wordbook[$1]}
  end
  sentence
end

puts expand("The quick <<COLOR>> <<ANIMAL_1>> jumps over the lazy <<ANIMAL_2>>", wordbook)
#=> The quick brown fox jumps over the lazy dog

也可以使用嵌套占位符:

wordbook = {
  "<<ADJECTIVE_1>>"=> "quick",
  "<<ADJECTIVE_2>>"=> "lazy",
  "<<COLOR>>"=> "brown",
  "<<ANIMAL_1>>"=> "<<ADJECTIVE_1>> <<COLOR>> fox",
  "<<ANIMAL_2>>"=> "the <<ADJECTIVE_2>> dog"
}

puts expand("The <<ANIMAL_1>> jumps over <<ANIMAL_2>>.", wordbook)
#=> The quick brown fox jumps over the lazy dog.

如果您有兴趣,链接的answer会从多种可能性中随机选择一个字符串。

答案 1 :(得分:1)

我不确定我是否深入理解了这个问题,对我来说,你的问题仍然不明确:用户何时以及应该由什么(以及如何由谁)代替什么? :)

无论如何,在谈到字符串替换和模板时,有时普通旧ruby 就足够了:

template = "The %{color} %{animal_1} jumps over the lazy %{animal_2}"
assignments = {color: 'black', animal_1: 'worm', animal_2: 'whitewalker'}
# pass Hash with substitution content
template % assignments #=> "The black worm jumps over the lazy whitewalker"

“字符串#%”在此处记录:https://ruby-doc.org/core-2.3.0/String.html#method-i-25

但如果你真的想要一个语法,那就选择另一个答案;)。如上所述,我的问题仍然不清楚。