title: Using bitly in Ruby on Rails
body: <p>I'm building a small application where users are able to post short messages and urls (twitter)</p>
  
  <p>To render the posts with urls in them I use the autolink gem <a href="https://github.com/tenderlove/rails_autolink" rel="nofollow">https://github.com/tenderlove/rails_autolink</a> and the following code, that extracts the urls from the text and turns them into links:</p>
  
  <pre><code>&lt;%= auto_link(feed_item.content) %&gt;
  </code></pre>
  
  <p>I also managed to render a shortened url by using the bitly api and bitly gem;
  <a href="https://github.com/philnash/bitly/" rel="nofollow">https://github.com/philnash/bitly/</a></p>
  
  <pre><code>&lt;%= auto_link(client.shorten("http://google.com").short_url) %&gt;
  </code></pre>
  
  <p>I've tried doing the shortening when the posts are created, using the following code in the model.</p>
  
  <pre><code>class Micropost &lt; 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
  </code></pre>
  
  <p>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?</p>