Home Carrierwave gem. How to rename uploaded image versions after recreating them?
Reply: 0

Carrierwave gem. How to rename uploaded image versions after recreating them?

user6293
1#
user6293 Published in September 19, 2018, 3:29 am

I have similar models as described in RailsCasts:

app/models/resident.rb:

class Resident < ActiveRecord::Base
  include PhotoConcern
end

app/models/employee.rb:

class Employee < ActiveRecord::Base
  include PhotoConcern
end

app/models/concerns/photo_concern.rb:

module PhotoConcern
  extend ActiveSupport::Concern

  included do
    mount_uploader :photo, PhotoUploader

    attr_accessor :photo_crop_x, :photo_crop_y, :photo_crop_w, :photo_crop_h

    after_save :crop_photo

    def crop_photo
      photo.recreate_versions! if photo_crop_x.present?
    end
  end
end

app/uploaders/photo_uploader.rb:

class PhotoUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  storage :file

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

  version :cropped do
    process :crop
  end

  version :thumb, from_version: :cropped do
    process resize_to_fill: [100, 100]
  end

  version :avatar, from_version: :cropped do
    process resize_to_fill: [200, 200]
  end

  def crop
    return if model.photo_crop_x.blank?

    resize_to_limit(500, nil)
    resize_to_fit(500, nil)

    manipulate! do |img|
      size = model.photo_crop_w << 'x' << model.photo_crop_h
      offset = '+' << model.photo_crop_x << '+' << model.photo_crop_y

      img.crop("#{size}#{offset}")
      img
    end
  end
end

app/views/employees/show.slim

= image_tag (@employee.photo.present? ? @employee.photo.url(:avatar) : "client_#{@employee.sex}.png"), class: 'img-circle img-responsive'

I want to rename version files after cropping so my users don't struggle with a cache. It's described in CarrierWave wiki how to rename files but also it's written "In order to save the newly generated filename you have to call save! on the model after recreate_versions!".

How can I rename version files? I can't call save! in my Employee's after_save again because there are more hooks that shouldn't be called twice. Also, PhotoConcern is included into another class.

Related wiki articles:

  • How to: Create random and unique filenames for all versioned files
  • How to: Customize your version file names
  • How to: Use a timestamp in file names
share|improve this question

1 Answer 1

active oldest votes
up vote 5 down vote
+100
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.584958 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO