【发布时间】:2018-11-09 05:58:07
【问题描述】:
我有类似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'
我想在裁剪后重命名版本文件,这样我的用户就不会为缓存而烦恼。 CarrierWave wiki 中描述了如何重命名文件以及 it's written“为了保存新生成的文件名,您必须在模型上调用 save! recreate_versions!”。
如何重命名版本文件?我不能再次在我的员工的after_save 中调用save!,因为有更多的钩子不应该被调用两次。此外,PhotoConcern 包含在另一个类中。
相关维基文章:
【问题讨论】: