我正在构建一个小应用程序,用户可以在其中发布短消息和网址 (twitter)

为了呈现带有 url 的帖子,我使用自动链接 gem https://github.com/tenderlove/rails_autolink 和以下代码,它从文本中提取 url 并将它们转换为链接:

<%= auto_link(feed_item.content) %>

我还设法通过使用 bitly api 和 bitly gem 来呈现缩短的 url;
https://github.com/philnash/bitly/
<%= auto_link(client.shorten("http://google.com").short_url) %>

我尝试在创建帖子时使用模型中的以下代码进行缩短。
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

即使链接显示在我的 bitly 仪表板中,也只有完整的 url 被保存到数据库中。这段代码有什么问题?

最佳答案

以下是您需要遵循的步骤

  • 首先需要提取消息中的所有URL
    urls = URI.extract(feed_item.content)
    
  • 然后用 Bitly 缩短 URLs 替换所有 URLs
    urls.each do |url|
      feed_item.content.gsub(url, client.shorten(url).short_url)
    end
    
  • 然后使用 auto_link
    <%= auto_link(feed_item.content) %>
    
  • 关于ruby-on-rails - 在 Ruby on Rails 中使用 bitly,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20761979/

    10-13 00:23