2012-11-14 24 views
1

再次提出新問題...我已經使用Bitly縮短了鏈接的代碼。RoR:使用Bitly搜索並縮短評論中的所有鏈接

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

這次我想做的是搜索並縮短註釋創建後的所有鏈接。這類似於這篇博客Using bitly in rails 3,但發現它有點混亂,因爲使用的循環,而不是 ... 塊。另外,我注意到這個方法甚至沒有被調用。在網站

樣品評論:

嘿,你應該檢查後http://vox4life.blogspot.com/2012/11/4Life-2012-Growth-is-strong.html而這一次.. http://vox4life.blogspot.com/2012/11/dengue-outbreak-peoples-journal.html另外這款 http://vox4life.blogspot.com/2012/02/transfer-factor-immunotherapy.html

會變成:

嘿,你應該檢查後http://bit.ly/ZHdLTa而這一次.. http://bit.ly/TZ6Nrj另外這款http://bit.ly/ZrnWMj

預先感謝您。

Similar question to this,但在Java

回答

1

如果你不希望一個循環我想你可以修改該法本身。我認爲這個正文是帶有URL的整個文本。

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 
+0

我會試試這個.. :) – jezureru

+0

很酷..它的工作..非常感謝你! – jezureru