有关carrierwave和mongoid的回调问题

时间:2011-03-18 14:54:26

标签: ruby-on-rails mongoid carrierwave

我在rails 3应用程序上使用了carrierwave和mongoid,并且遇到了after_save回调问题。请考虑以下

class Video
  include Mongoid::Document

  field :name  

  mount_uploader :file, VideoUploader

  after_create :enqueue_for_encoding

  protected

  def enqueue_for_encoding
     // point your encoding service to where it expects the permanent file to reside
     // in my case on s3 
  end

end

我的问题是在我的enqueue_for_encoding方法中,file.url指向本地tmp目录而不是s3目录。

当file.url指向s3时,如何调用enqueue_for_encoding方法?

谢谢!

乔纳森

4 个答案:

答案 0 :(得分:2)

在Callbacks上查看carrierwave的howto页面

https://github.com/jnicklas/carrierwave/wiki/How-to%3A-use-callbacks

它对我有用

答案 1 :(得分:1)

好的,我明白了。采取了一些黑客攻击。因此,当前的carrierwave不会公开after_create挂钩,所有挂起和处理都会在after_save回调中发生。以下是我用来解决它的代码:

# Video.rb

  mount_uploader :file, VideoUploader

  # overwrite the file setting to flag the model that we are creating rather than saving
  def file=(obj)
    @new_file = true
    super(obj)
  end

  # chain the store_file! method to enqueue_for_encoding after storing the file AND
  # if the file is new
  alias_method :orig_store_file!, :store_file!
  def store_file!
    orig_store_file!
    if @new_file #means dirty
      @new_file = false
      enqueue_for_encoding
    end
    true
  end

<强>更新

Woops - 没用。它几乎做到了 - 网址是正确的,但它是永久性的。意味着文件仍在加载过程中,并且在调用enqueue_for_encoding时未完全存储

答案 2 :(得分:1)

可以在上传器本身设置enqueue_for_encoding回调。但我更喜欢这样做:

class Video
  # mount the uploader first:
  mount_uploader :file, VideoUploader
  # then add the callback:
  after_save :enqueue_for_encoding, on: :create
end

答案 3 :(得分:0)

您可以尝试删除模型中的after_create回调,并将以下内容添加到您的上传器中:

# video_uploader.rb

process :encode

def encode
  model.enqueue_for_encoding
end

在保存文件之后,process回调被称为(我认为),这应该允许您在S3上启动文件时挂钩。