Ruby on Rails - Converting Twitter @mentions, #has

2019-04-02 02:29发布

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 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

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!

2条回答
贪生不怕死
2楼-- · 2019-04-02 02:59

Use jQuery Tweet Linkify

A small jQuery plugin that transforms @mention texts into hyperlinks pointing to the actual Twitter profile, #hashtag texts into real hashtag searches, as well as hyperlink texts into actual hyperlinks

查看更多
地球回转人心会变
3楼-- · 2019-04-02 03:03

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.

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

Full code:

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)

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>
查看更多
登录 后发表回答