ruby-on-rails - Ruby on Rails - 在字符串中转换 Twitter @mentions、#hashtags 和 URL

标签 ruby-on-rails twitter

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

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

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

  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 ,则将其添加到您的 Gemfile (gem 'twitter-text') 中并执行以下操作: 捆绑安装

然后在类的顶部包含 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>

关于ruby-on-rails - Ruby on Rails - 在字符串中转换 Twitter @mentions、#hashtags 和 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12547496/

相关文章:

ruby-on-rails - Codeship - 捆绑安装错误(您必须使用捆绑程序 2 或更高版本与此锁定文件)

ruby-on-rails - FakeFS 和 Rspec 与 Rspec 和真实文件系统不一致

python - Tweepy 语法和 Twitter 流 api

java - twitter4j 地理流媒体 新加坡及其他地区的纬度/经度

iphone - 在 iOS 5.1 中从应用程序打开 Twitter 设置

ruby-on-rails - Rails Where Created_at 等于特定数字

ruby-on-rails - Where 条件与 rails

ruby-on-rails - 更多 gem 安装 rails 令人头疼

ios - 无法快速获取推特用户详细信息

javascript - 使用nodejs从twitter API检索超过100条推文