如何在Carrierwave中自定义版本文件名?

时间:2015-07-30 17:05:06

标签: ruby-on-rails ruby-on-rails-3

我有一个奇怪的问题。我正在尝试使用带有Rails 3.2.xx项目的carrierwave的master分支。我需要自定义版本的文件名。但是当我在版本块中添加full_filename方法时,我的原始文件也会减少到为版本指定的尺寸。

当我删除full_filename方法时,它全部按预期工作,但是thumb filename有thumb_前缀,我不想要。

是否有新的方法来自定义版本文件名。我一直在0.10.0和之前成功使用这种方式。

以下是我的上传者。这是一个生成的上传器store_dir覆盖。

class TestUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  # storage :file
  storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Create different versions of your uploaded files:

  version :thumb do
    process :resize_to_fit => [200, 200]

    def store_dir
      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}/#{version_name}"
    end

    def full_filename(for_file = model.logo.file)
      super(for_file).sub(version_name.to_s + '_', '')
    end
  end

end

有什么想法吗?我需要做的就是从文件名中删除version_name部分,因为我将版本保存在单独的文件夹中。我搜索了维基和互联网,但找不到新的方法。

1 个答案:

答案 0 :(得分:0)

添加初始化程序 carrierwave.rb 并使用以下内容对gem进行mokeypatch:

module CarrierWave
  module Uploader
    module Versions
      private
        # Use original file name instead of prepending version name
        # Can't overload in app's uploader class because `super` already has
        # the version name
        def full_filename(for_file)
          directory = version_name.to_s
          # if you want the original version in a sub-directory also
          # directory = (version_name || 'original').to_s
          File.join(directory, super(for_file))
        end
    end
  end
end

另外,请不要使用版本中的store_dirfull_filename方法。