Search code examples
ruby-on-railshyperlinkurl-shortener

RoR: Search and shorten all links in a comment using Bitly


Newbie question again... I already have the following code for making links shortened using Bitly.

def bitly_links(url)                                     
 bitly ||= begin                                            
  Bitly.use_api_version_3                                     
  Bitly.new('username', 'key')
  bitly.shorten(url)
 end
end

What I'd like to do this time is to search for and shorten all links in a comment after it's been created. This is similar to this blog post Using bitly in rails 3, but found it a bit confusing because of the use of for loop instead of the do...end block. Also, I notice that the method was not even called.

Sample comment in the website:

Hey, you should check out the post http://vox4life.blogspot.com/2012/11/4Life-2012-Growth-is-strong.html and this one.. http://vox4life.blogspot.com/2012/11/dengue-outbreak-peoples-journal.html Also this http://vox4life.blogspot.com/2012/02/transfer-factor-immunotherapy.html

Would turn into:

Hey, you should check out the post http://bit.ly/ZHdLTa and this one.. http://bit.ly/TZ6Nrj Also this http://bit.ly/ZrnWMj

Thank you in advance.

Similar question to this, but in Java


Solution

  • If you do not want a for loop I guess you could modify the method as such. I'm figuring that body is the entire text with URLs.

    def bitly_body(body)
        matches = body.scan(/((http|https):\/\/(\&|\=|\_|\?|\w|\.|\d|\/|-)+(:\d+(\&|\=|\?|\w|\.|\d|\/|-)+)?)/)
        Bitly.use_api_version_3
    
        bitly = Bitly.new("thealey", "bitly_api_key")
    
        (0..matches.length).each do |i|    # <-- changed here.
          if matches[i].to_s.size > 0
            logger.info("url " + matches[i][0])
            if matches[i][0].include? "bit.ly"
              logger.info("already a bitly url " + matches[i][0])
            else
              u = bitly.shorten(matches[i][0])
              body[matches[i][0]] = u.short_url
            end
          end
        end
        body
    end