【问题标题】:callback issue with carrierwave and mongoid载波和 mongoid 的回调问题
【发布时间】:2011-03-18 14:54:25
【问题描述】:

我在 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 方法?

谢谢!

乔纳森

【问题讨论】:

    标签: ruby-on-rails mongoid carrierwave


    【解决方案1】:

    查看carrierwave关于回调的howto页面

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

    对我有用

    【讨论】:

      【解决方案2】:

      好的,我想通了。采取了一些黑客攻击。因此,目前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
      

      更新

      糟糕——那没用。它几乎做到了——网址是正确的,但它被永久解雇了。表示文件仍在加载过程中,调用 enqueue_for_encoding 时未完全存储

      【讨论】:

        【解决方案3】:

        可以在上传器本身上设置您的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
        

        【讨论】:

          【解决方案4】:

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

          # video_uploader.rb
          
          process :encode
          
          def encode
            model.enqueue_for_encoding
          end
          

          process 回调被调用文件被保存(我认为)这应该允许你在你的文件在 S3 上启动后挂钩。

          【讨论】:

          • 感谢人的评论——但它不起作用——甚至进程回调指向临时文件。
          • 该死的。这真的很烦人。您能否在您的应用程序中使用 cron 作业来扫描您的 S3 存储桶/目录以查找未处理的作业并以这种方式将它们添加到队列中?不那么优雅,但应该可以可靠地完成任务。
          猜你喜欢
          • 2011-09-07
          • 1970-01-01
          • 2012-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多