I'm building a small application where users are able to post short messages and urls (twitter)
To render the posts with urls in them I use the autolink gem https://github.com/tenderlove/rails_autolink and the following code, that extracts the urls from the text and turns them into links:
<%= auto_link(feed_item.content) %>
I also managed to render a shortened url by using the bitly api and bitly gem; https://github.com/philnash/bitly/
<%= auto_link(client.shorten("http://google.com").short_url) %>
I've tried doing the shortening when the posts are created, using the following code in the model.
class Micropost < ActiveRecord::Base
before_create :bitly_shorten
private
def bitly_shorten
client = Bitly.client
urls = URI.extract(self.content)
urls.each do |url|
self.content.gsub(url, client.shorten(url).short_url)
end
end
end
Even though the links show up in my bitly dashboard, only the full urls are saved to the database. What is wrong with this code?
Below are the steps that you need to follow
First, you need to extract all the URLs in the message
Then replace all the URLs with Bitly shorten URLs
Then use auto_link