New     Submit     Search     Register  

How To Add Rel=Nofollow To All Links In A Ruby On Rails App

Kirill Zubovsky / August 8th, 2020

If you run a content website like Smash Notes, at some points it becomes important to tell Google and other search engines which links to follow and which to ignore. In our case, Google should follow all links to podcaster's own website, but at the same time ignore all the hundreds of links that might be mentioned in descriptions. Only a few links on the page should matter. Smash Notes is written in Ruby on Rails, and upon a quick glance there is no built-in solution to auto-assign attributes to some links, and ignore others. You can add anything to link_to attribute, but if the content comes from a third party, like a Podcast description, then links are already based in. What are you to do? To be honest, I don't know for certain if there is a more proper solution, but the solution that works is simple. Gsub! Here is how I take all the links in segments, episode and podcast descriptions, and return them with ref=nofollow. sanitize(simple_format(@Public_Summary).gsub('<a ','<a rel='nofollow''), tags: %w(a), attributes: %w(href rel)) @Public_Summary in this case is the variable that contains each summary. Simply format turns wraps it into a paragraph, gsub adds new attribute to the link, and sanitize makes sure no funny business is returned to the end user. Is there a better way? Probably. Even better way would be to write a function that formats all the text on save, and then stores it in the database with the right tags, so as to not spend any extra time on render. But this method works for now, it's easy, fast, and it works! Bonus: If your sanitize() is set to allow <a> elements, then ironically the code block above will not render, as it will actually turn everything after <a into a link. The way to get around this is by using ASCII characters.

One podcast summary every day.

Get thoughtful insights from podcasts in a minute or less. Editor's choice, delivered every Wednesday. It's free!