Skip to content

Instantly share code, notes, and snippets.

@GesJeremie
Created September 26, 2023 15:16
Show Gist options
  • Save GesJeremie/50d9d26bdc6bcfa771d23dda8f172c63 to your computer and use it in GitHub Desktop.
Save GesJeremie/50d9d26bdc6bcfa771d23dda8f172c63 to your computer and use it in GitHub Desktop.
Rake task to create thumbnails of static images
require 'mini_magick'
namespace :covers do
def covers_path
Rails.root.join('app', 'assets', 'images', 'covers')
end
def files_inside_covers_path
Dir.glob(covers_path.to_s << '/**/*').select { |path| File.file?(path) }
end
def covers
files_inside_covers_path.reject { |path| path.include?('_thumbnail') }
end
def thumbnails
files_inside_covers_path.select { |path| path.include?('_thumbnail') }
end
desc 'Generate thumbnails versions of existing covers'
task :create_thumbnails do
covers.each do |cover_path|
destination_path = cover_path.gsub('.jpg', '_thumbnail.jpg')
MiniMagick::Image.open(cover_path).tap do |cover|
cover.resize('32%')
cover.write(destination_path)
end
end
end
desc 'Delete thumbnails versions of existing covers'
task :destroy_thumbnails do
thumbnails.each do |thumbnail_path|
File.delete(thumbnail_path)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment