ruby-on-rails - 如何在 Ruby/Rails 中匹配和替换模板标签?

标签 ruby-on-rails ruby regex templates

尝试向我的一个 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/

相关文章:

ruby-on-rails - 如何忽略一些 rails_best_practices gem 警告?

ruby - 如何在 Bluehost 上安装特定版本的 Ruby 和 Rails?

regex - 在 Swift 中查找括号之间的文本

python - 我无法理解奇怪的行为

ruby-on-rails - 如何安排 Rails 邮件在特定日期发送 (heroku)?

ruby-on-rails - 我们如何删除 Rails 中的 session ?

ruby-on-rails - Ruby 在 X 分钟后运行

ruby-on-rails - ActiveRecord::Base.store 自动类型转换

ruby-on-rails - Rails : Validating that start is before stop, 日期时间

Javascript 正则表达式匹配无法正确运行