【问题标题】:Ruby on Rails: bbc-code and performanceRuby on Rails:bbc 代码和性能
【发布时间】:2012-04-13 15:32:00
【问题描述】:

我在 Rails 应用程序中使用 bb-code 来发帖和 cmets。目前,我有以下内容可以将帖子的内容放在视图中:

<%= @post.content.bbcode_to_html.html_safe.gsub('<a', '<a rel="nofollow"') %>

将 bb-code 转换为 html 并将“nofollow”添加到所有链接的最佳方法是什么?

谢谢!

【问题讨论】:

    标签: ruby-on-rails bbcode


    【解决方案1】:

    您正在使用的bb-ruby gem 允许使用作为参数传递给bbcode_to_html 方法的自定义BBCode 翻译。但是,如果您真的希望 ALL 链接包含rel="nofollow",我认为您最好的选择是猴子修补它们本身的宝石。基于BBRuby source,你想这样做:

    module BBRuby
      @@tags = @@tags.merge({
        'Link' => [
          /\[url=(.*?)\](.*?)\[\/url\]/mi,
          '<a href="\1" rel="nofollow">\2</a>',
          'Hyperlink to somewhere else',
          'Maybe try looking on [url=http://google.com]Google[/url]?',
          :link],
        'Link (Implied)' => [
          /\[url\](.*?)\[\/url\]/mi,
          '<a href="\1" rel="nofollow">\1</a>',
          'Hyperlink (implied)',
          "Maybe try looking on [url]http://google.com[/url]",
          :link],
        'Link (Automatic)' => [
          /(\A|\s)((https?:\/\/|www\.)[^\s<]+)/,
          ' <a href="\2" rel="nofollow">\2</a>',
          'Hyperlink (automatic)',
          'Maybe try looking on http://www.google.com',
          :link]
        })
    end
    

    这将重写 BBRuby 翻译器以始终包含 nofollow 属性。我会将它放在config/initializers 中,并带有描述性文件名,例如bbruby_nofollow_monkeypatch.rb

    至于html_safe,我会保持原样。据我了解,这是一种首选方式,并且我认为它可以使您的意图清晰。上面的猴子补丁使您视图中的行更具可读性:

    <%= @post.content.bbcode_to_html.html_safe %>
    

    【讨论】:

    • 行得通,谢谢!由于我对 Rails 还很陌生,所以看看如何用猴子修补 gem 是很有趣的。
    • 没问题,但你知道你必须手动奖励我赏金:stackoverflow.com/faq#bounty
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多