【问题标题】:Ruby on Rails - Converting Twitter @mentions, #hashtags and URLs within a stringRuby on Rails - 在字符串中转换 Twitter @提及、#hashtags 和 URL
【发布时间】:2012-09-14 21:03:57
【问题描述】:

假设我有一个包含从 Twitter 抓取的文本的字符串,如下所示:

myString = "I like using @twitter, because I learn so many new things! [line break]
Read my blog: http://www.myblog.com #procrastination"

然后在视图中显示推文。但是,在此之前,我想转换字符串,以便在我看来:

  1. @twitter 链接到http://www.twitter.com/twitter
  2. URL 变成了链接(其中 URL 仍然是链接文本)
  3. #procrastination 变成https://twitter.com/i/#!/search/?q=%23procrastination,其中#procrastination 为链接文字

我确信那里一定有一颗宝石可以让我这样做,但我找不到。我遇到过twitter-text-rb,但我不知道如何将它应用到上面。我已经使用正则表达式和其他一些方法在 PHP 中完成了它,但它有点乱!

提前感谢任何解决方案!

【问题讨论】:

    标签: ruby-on-rails twitter


    【解决方案1】:

    twitter-text gem 为您提供了几乎所有的工作。手动安装它(gem install twitter-text,如果需要,使用 sudo)或将它添加到您的 Gemfile(gem 'twitter-text')如果您使用的是 bundler 并执行bundle install

    然后在你的类的顶部包含 Twitter 自动链接库(require 'twitter-text'include Twitter::Autolink)并使用输入字符串作为参数调用方法auto_link(inputString),它会给你自动链接版本

    完整代码:

    require 'twitter-text'
    include Twitter::Autolink
    
    myString = "I like using @twitter, because I learn so many new things! [line break] 
    Read my blog: http://www.myblog.com #procrastination"
    
    linkedString = auto_link(myString)
    

    如果你输出linkedString的内容,你会得到如下输出:

    I like using @<a class="tweet-url username" href="https://twitter.com/twitter" rel="nofollow">twitter</a>, because I learn so many new things! [line break] 
    Read my blog: <a href="http://www.myblog.com" rel="nofollow">http://www.myblog.com</a> <a class="tweet-url hashtag" href="https://twitter.com/#!/search?q=%23procrastination" rel="nofollow" title="#procrastination">#procrastination</a>
    

    【讨论】:

    • 啊,太棒了,谢谢。所以,在我看来,我认为我需要使用“auto_link”之类的东西来确保链接正确显示?
    • 为了澄清我上面的查询,我的视图将字符串显示为纯文本,即链接不是 HTML 链接。因此,文本已正确转换,但在我看来并未按预期显示。
    • 该工具添加了相关标记,以将链接转换为实际的 HTML 链接,用于标签、用户名和推文中的链接。您能否发布它的显示方式和应该如何显示的屏幕截图?
    • 知道了 - 我必须将 .html_safe 添加到字符串的末尾,即在我的视图中显示以上内容,代码类似于&lt;p&gt;&lt;%= linkedString.html_safe %&gt;
    • 是的,如果您使用的是 Rails,这将是必要的。我以为这是一般的 Ruby 本身,但很高兴你把它分类了
    【解决方案2】:

    使用jQuery Tweet Linkify

    一个小型 jQuery 插件,可将 @mention 文本转换为指向实际 Twitter 个人资料的超链接,将 #hashtag 文本转换为真正的主题标签搜索,以及将超链接文本转换为实际超链接

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 2014-05-14
      • 2012-02-23
      • 1970-01-01
      相关资源
      最近更新 更多