在rails中用<a href="/phrase">phrase</a>替换{phrase}

时间:2014-03-22 06:32:46

标签: ruby-on-rails ruby

我想使用rails(erb.html文件)搜索并替换任何出现的{phrase}和<a href="/phrase">phrase</a>。需要替换多个短语,并且事先不知道这些短语。

完整示例:

Hi {guys}, I really like {ruby on rails}

需要成为

Hi <a href="/guys">guys</a>, <a href="/ruby on rails">ruby on rails</a>

这适用于用户生成的内容网站(GMT

4 个答案:

答案 0 :(得分:4)

这是简单的正则表达式,只需使用

your_string.gsub(/{(.*?)}/, '<a href="\\1">\\1</a>')

示例:

"{aaa} is not {bbb} you know".gsub(/{(.*?)}/, '<a href="/\\1">\\1</a>')

将产生

<a href="/aaa">aaa</a> is not <a href="/bbb">bbb</a> you know

答案 1 :(得分:1)

您可以使用gsub

执行此操作
irb(main):001:0> str = " I have written this phrase statement, I want to replace occurences of all phrase with other statement"
=> " I have written this phrase statement, I want to replace occurences of all phrase with other statement"
irb(main):002:0> str.gsub("phrase",'<a href="/phrase">phrase</a>')
=> " I have written this <a href=\"/phrase\">phrase</a> statement, I want to replace occurences of all <a href=\"/phrase\">phrase</a> with other statement"

答案 2 :(得分:1)

更好的方法是使用Markdown输出引擎(Redcarpet是最强大的引擎之一)

您必须创建custom renderer

#lib/custom_renderer.rb
class AutoLinks < Redcarpet::Render::HTML
  def auto_link(phrase) #-> will need to search through content. Can research further
    link_to phrase, "/#{phrase}"
  end
end

#controller
markdown = Redcarpet::Markdown.new(AutoLinks, auto_link: "ruby on rails")

答案 3 :(得分:0)

只需在你的erb中使用帮助器。例如:

<强> tag_helper.rb:

module TagHelper
  def atag(phrase)
    "<a href='/#{phrase}'>#{phrase}</a>"
  end
end

<强> some.html.erb:

<%= atag('guys')%>