Last active
October 6, 2015 19:29
-
-
Save krisdigital/dc9d3138fb99857ab962 to your computer and use it in GitHub Desktop.
Rails Dragonfly delete unused files
This file contains 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
class Image < ActiveRecord::Base | |
belongs_to :imageable, :polymorphic => true | |
dragonfly_accessor :image | |
validates_property :format, of: :image, in: ['jpeg', 'png', 'gif'] | |
validates :image, presence: true | |
def self.cleanup | |
image_root = Dragonfly.app.datastore.root_path | |
self.clean_folder(image_root) | |
end | |
def self.clean_folder(folder) | |
image_root = folder | |
meta_ending = ".meta.yml" | |
Dir.foreach(folder) do |item| | |
next if item == '.' or item == '..' | |
path_to_check = File.join(image_root, item) | |
if File.directory? path_to_check | |
self.clean_folder(path_to_check) | |
next | |
end | |
if item.last(meta_ending.length) == meta_ending | |
next | |
end | |
subfolder = image_root.dup | |
subfolder.slice!( Dragonfly.app.datastore.root_path ) | |
item_name = File.join(subfolder, item) | |
if item_name[0] == "/" | |
item_name.slice!(0) | |
end | |
file = File.join(image_root, item) | |
unless Image.find_by(image_uid: item_name) && File.mtime(file) < 3.days.ago | |
File.delete(file) | |
begin | |
File.delete(file + meta_ending) | |
rescue Exception => e | |
end | |
puts "Process: #{file}" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment