Ruby on Rails – 在字符串中转换Twitter @mentions,#hashtgs和URL

假设我有一个字符串,其中包含从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是链接文本

我敢肯定那里必须有一颗gem可以让我这样做,但我找不到一颗。 我遇到过twitter-text-rb,但我不太清楚如何将它应用到上面。 我使用正则表达式和其他一些方法在PHP中完成它,但它有点乱!

在此先感谢任何解决方案!

twitter-text gem几乎涵盖了所有的工作。 手动安装( gem install twitter-text ,如果需要可以使用sudo)或者如果你使用的是Bundler并进行bundle install则将其添加到你的Gemfile(gem’trip gem 'twitter-text' )。

然后在类的顶部包含Twitter自动链接库( require 'twitter-text'include Twitter::Autolink auto_link(inputString)并使用输入字符串作为参数调用方法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 @twitter, because I learn so many new things! [line break] Read my blog: http://www.myblog.com #procrastination 

使用jQuery Tweet Linkify

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