尝试向我的一个 Rails 模型添加一个非常基本的描述模板。我想要做的是采用这样的模板字符串:
template = "{{ name }} is the best {{ occupation }} in {{ city }}."
和这样的散列:
vals = {:name => "Joe Smith", :occupation => "birthday clown", :city => "Las Vegas"}
并生成描述。我以为我可以用一个简单的 gsub 来做到这一点,但 Ruby 1.8.7 不接受散列作为第二个参数。当我像这样将 gsub 作为 block 执行时:
> template.gsub(/\{\{\s*(\w+)\s*\}\}/) {|m| vals[m]}
=> " is the best in ."
您可以看到它用整个字符串(带花括号)替换了它,而不是匹配捕获。
如何用 vals["something"](或 vals["something".to_sym])替换“{{ something }}”?
TIA
最佳答案
使用 Ruby 1.9.2
string formatting operator %
将格式化一个带有散列的字符串作为 arg
>> template = "%{name} is the best %{occupation} in %{city}."
>> vals = {:name => "Joe Smith", :occupation => "birthday clown", :city => "Las Vegas"}
>> template % vals
=> "Joe Smith is the best birthday clown in Las Vegas."
使用 Ruby 1.8.7
The string formatting operator in Ruby 1.8.7 doesn't support hashes .相反,您可以使用与 Ruby 1.9.2 解决方案相同的参数并修补 String 对象,这样当您升级 Ruby 时就不必编辑字符串。
if RUBY_VERSION < '1.9.2'
class String
old_format = instance_method(:%)
define_method(:%) do |arg|
if arg.is_a?(Hash)
self.gsub(/%\{(.*?)\}/) { arg[$1.to_sym] }
else
old_format.bind(self).call(arg)
end
end
end
end
>> "%05d" % 123
=> "00123"
>> "%-5s: %08x" % [ "ID", 123 ]
=> "ID : 0000007b"
>> template = "%{name} is the best %{occupation} in %{city}."
>> vals = {:name => "Joe Smith", :occupation => "birthday clown", :city => "Las Vegas"}
>> template % vals
=> "Joe Smith is the best birthday clown in Las Vegas."
codepad example showing the default and extended behavior
关于ruby-on-rails - 如何在 Ruby/Rails 中匹配和替换模板标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6258516/