Question

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?

Was it helpful?

Solution

Below are the steps that you need to follow

  1. First, you need to extract all the URLs in the message

    urls = URI.extract(feed_item.content) 
    
  2. Then replace all the URLs with Bitly shorten URLs

    urls.each do |url|
      feed_item.content.gsub(url, client.shorten(url).short_url)  
    end
    
  3. Then use auto_link

    <%= auto_link(feed_item.content) %> 
    

OTHER TIPS

You should probably perform the shortening when the user creates the post.

When you create the post, extract all the links from the message and shorten them. Then you will only need to display the content at runtime.

This is more efficient because it will prevent the page to call the shortener service every time the view is rendered.

after trying out the code in the console, I realized that I missed the ! after gsub, that kept the replaced url from being saved to the database..

The following solution works for me;

class Micropost < ActiveRecord::Base
  before_validation :bitly_shorten #shorten before the 150 character limit validation

  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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top