加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:19:07 所属栏目:百科 来源:网络整理
导读:试图在我的一个Rails模型中添加一个非常基本的描述模板.我想要做的是采取这样的模板字符串: template = "{{ name }} is the best {{ occupation }} in {{ city }}." 和这样的哈希: vals = {:name = "Joe Smith",:occupation = "birthday clown",:city = "L
试图在我的一个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作为一个块:

> 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",: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",:city => "Las Vegas"}
>> template % vals
=> "Joe Smith is the best birthday clown in Las Vegas."

codepad example showing the default and extended behavior

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读