假设我有一个字符串,其中包含从 Twitter 抓取的文本,如下所示:
myString = "I like using @twitter, because I learn so many new things! [line break]
Read my blog: http://www.myblog.com #procrastination"
然后该推文将显示在 View 中。但是,在此之前,我想转换字符串,以便在我看来:
- @twitter 链接到 http://www.twitter.com/twitter
- URL 被转换为链接(其中 URL 仍为链接文本)
- #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/