【问题标题】:RoR: Search and shorten all links in a comment using BitlyRoR:使用 Bitly 搜索和缩短评论中的所有链接
【发布时间】:2012-11-14 08:27:23
【问题描述】:

又是新手问题...我已经有了以下代码,用于使用 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 类似,但由于使用了 for 循环而不是 do 循环,因此有点令人困惑。 ..结束块。另外,我注意到该方法甚至没有被调用。

网站中的示例评论:

嘿,你应该看看帖子 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 中

【问题讨论】:

    标签: ruby-on-rails hyperlink url-shortener


    【解决方案1】:

    如果您不想要 for 循环,我想您可以修改该方法。我认为正文是带有 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
    

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多