Created
December 5, 2019 14:19
-
-
Save airled/f2f3302955e96b2674c5d27c032f1bca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Carrierwave works incorrectly with file formatting. If you do not override | |
# path and url methods it will return you incorrect path and url to webp file | |
# respectively. Also you should add removing callback because Carrierwave could | |
# not delete webp file by itself because of incorrect path. | |
# Remove this hacks if this issue will be fixed. | |
class ItemGalleryUploader < ApplicationUploader | |
WEBP_VERSION_NAME = :webpver | |
WEBP_CONV_OPTIONS = {quality: 80, method: 5}.freeze | |
before :remove, :clear_webp_file | |
version WEBP_VERSION_NAME do | |
process :convert_to_webp | |
def path | |
incorrect_path = super.split('.') | |
incorrect_path.pop | |
incorrect_path.join('.') + '.webp' | |
end | |
def url | |
incorrect_path = super.split('.') | |
incorrect_path.pop | |
incorrect_path.join('.') + '.webp' | |
end | |
end | |
private | |
def convert_to_webp | |
return if file.content_type.include?('image/svg') | |
file_path = file.path.split('.') | |
file_path.pop | |
webp_file_path = file_path.join('.') + '.webp' | |
WebP.encode(file.path, webp_file_path, WEBP_CONV_OPTIONS) | |
@filename = webp_file_path.split('/').last | |
@file = CarrierWave::SanitizedFile.new( | |
tempfile: webp_file_path, | |
filename: @filename, | |
content_type: 'image/webp' | |
) | |
end | |
def clear_webp_file | |
path = self.try(WEBP_VERSION_NAME).try(:path) | |
return unless path && File.exist?(path) | |
File.unlink(path) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment