本文介绍了Ruby on Rails - 在字符串中转换 Twitter @mentions、#hashtags 和 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a string which contains text grabbed from Twitter, as follows:

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

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

The tweet is then presented in a view. However, prior to this, I'd like to convert the string so that, in my view:

  1. @twitter 链接到 http://www.twitter.com/twitter
  2. URL 变成了链接(其中 URL 仍然是链接文本)
  3. #procrastination 变成了 https://twitter.com/i/#!/search/?q=%23procrastination,其中#procrastination 是链接文本
  1. @twitter links to http://www.twitter.com/twitter
  2. The URL is turned into a link (in which the URL remains the link text)
  3. #procrastination is turned into https://twitter.com/i/#!/search/?q=%23procrastination, in which #procrastination is the link text

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

I'm sure there must be a gem out there that would allow me to do this, but I can't find one. I have come across twitter-text-rb but I can't quite work out how to apply it to the above. I've done it in PHP using regex and a few other methods, but it got a bit messy!

预先感谢您提供任何解决方案!

Thanks in advance for any solutions!

推荐答案

twitter-textgem 为您提供了几乎所有的工作.手动安装(gem install twitter-text,如果需要,使用 sudo)或将它添加到你的 Gemfile(gem 'twitter-text'),如果你正在使用 bundler 并且做捆绑安装.

The twitter-text gem has pretty much all the work covered for you. Install it manually (gem install twitter-text, use sudo if needed) or add it to your Gemfile (gem 'twitter-text') if you are using bundler and do bundle install.

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

Then include the Twitter auto-link library (require 'twitter-text' and include Twitter::Autolink) at the top of your class and call the method auto_link(inputString) with the input string as the parameter and it will give you the auto linked version

完整代码:

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的内容,会得到如下输出:

If you output the contents of linkedString, you get the following output:

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 - 在字符串中转换 Twitter @mentions、#hashtags 和 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 15:51