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:
- @twitter links to http://www.twitter.com/twitter
- The URL is turned into a link (in which the URL remains the link text)
- #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!
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
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 dobundle install
.Then include the Twitter auto-link library (
require 'twitter-text'
andinclude Twitter::Autolink
) at the top of your class and call the methodauto_link(inputString)
with the input string as the parameter and it will give you the auto linked versionFull code:
If you output the contents of linkedString, you get the following output: