使用Ruby将多个映像上传到Imgur API很慢

时间:2015-10-14 02:31:36

标签: ruby-on-rails ruby api image-uploading imgur

所以我有一个可以一次提交多个图像的表单。我还在Ruby中为Imgur API编写了一个包装器。我的问题是,由于这种情况完全同步发生,因此即使10张图像也需要永久和超时。我想知道是否有更好的方法可以处理更多图像。

我所能想到的只是异步提交每张一张图片的表单,但我不确定这是不是一个好主意,或者它是否会阻止其他请求。

class MissionsController < ApplicationController
  def add_images
    image_ids = params[:images].collect do |image|
      Image.with_imgur(
        title: "#{@mission.trip.name} - #{current_user.username}",
        image: image,
        album_id: @mission.album.imgur_id,
        user_id: current_user.id,
        trip_id: @mission.trip_id
      ).imgur_id
    end
  end
end

class Image < ActiveRecord::Base
  def self.with_imgur(options)
    trip_id = options.delete(:trip_id)
    user_id = options.delete(:user_id)
    image = Imgur::Image.create(options)
    create(
      imgur_id: image["id"],
      link: image["link"],
      trip_id: trip_id,
      user_id: user_id
    )
  end
end

https://github.com/tomprats/toms-missions/blob/master/app/models/imgur.rb#L116

class Imgur::Image < Base
  def self.create(options)
    url = "https://api.imgur.com/3/image"
    params = {
      image: options[:image],
      album: options[:album_id],
      type: options[:type] || "file", # "file" || "base64" || "URL"
      title: options[:title],
      description: options[:description]
    }
    api_post(url, params).body["data"]
  end
end

1 个答案:

答案 0 :(得分:0)

我要看看Typhoeus https://github.com/typhoeus/typhoeus - 我过去曾用过这个来处理上传等等到Amazon Glacier。我发现它可以更快--Typhoeus为您提供了一个未来的对象,并将在后台处理您的上传而不会阻止应用程序。

我希望这有帮助!