【问题标题】:Carreirwave - How to have the version name created directly from the saved filenameCarreirwave - 如何直接从保存的文件名创建版本名称
【发布时间】:2016-09-19 10:24:30
【问题描述】:

我正在为已上传到我的应用程序的文件创建缩略图。图像名称中包含时间戳代码。当我运行recreate_versions 时,生成的缩略图中也包含时间戳,但它使用当前时间戳,这使得缩略图名称与原始文件名不同。

所以我想一个解决方法是为拇指图像设置一个自定义文件名。基本上有'thumb_' + '原始文件名'。

   version :thumb do
     process :resize_to_limit => [110, nil]

     def full_filename(for_file = model.image_value.file)
     'thumb_' + File.basename(model.image_value.path).to_s
     end
   end

  def filename(for_file = model.image_value.file)
   "#{model.id}" + "-v#{timestamp}" + "-" + "#{model.name}" + ".png" if original_filename.present?
  end

  def timestamp
    var = :"@#{mounted_as}_timestamp"
    model.instance_variable_get(var) or model.instance_variable_set(var, Time.now.to_i)
  end

这似乎是一个简单的解决方法,但由于某种原因,当我运行recreate_versions 时,生成的缩略图中包含当前时间戳,而不是原始文件名中的时间戳。据我了解,它应该获取存储在数据库中的原始文件名值,并将其添加到“thumb_”的末尾。但不知何故,它改变了名称中的时间戳。

stored filename                      =       1-v1474175808-model-name.png
Item.find(1).image_value_url(:thumb) = thumb_1-v1474175808-model-name.png #this works correctly and looks for the correct filename
thumb filename saved                 = thumb_1-v1472111618-model-name.png #thumb saved is different. For some reason has a different timestamp in name

我认为def full_filename 可能没有运行,但如果我将其更改为其他内容,则保存的拇指文件名将更改为 def full_filename 中的内容。

不确定这里发生了什么。希望有人可以提供帮助。如果它看起来应该可以工作,请告诉我,至少这会澄清它可能不是我在看的东西。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 carrierwave rmagick


    【解决方案1】:

    最终不得不使用生成的 url 并在 url 上使用 slice! 以仅保留图像名称。

       version :thumb do
         process :resize_to_limit => [110, nil]
    
        def full_filename(for_file = model.image_value.file)
          raw_file_name = model.image_value.slice!(0..65)
         'thumb_' + raw_file_name
         end
    
      end
    

    【讨论】:

      【解决方案2】:

      我不明白你为什么使用instance_variable_getset。为什么不直接使用Itemcreated_at?那么它就永远不会改变了。

      def timestamp      
        model.created_at
      end
      

      【讨论】:

      • 因为在图片更新的时候名字需要改变并且是uniq的。
      • 所以您需要所有版本都有一个新的、唯一的名称?
      • 不,版本只需要与原始文件具有相同的名称,但在其名称前面添加“thumb_”即可。
      • 那么时间戳的作用是什么,它必须从Time.now.to_i生成,而不是从上传器安装的模型中获取时间戳?
      猜你喜欢
      • 2021-08-09
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      相关资源
      最近更新 更多