public
Description: Paperclip File Management Plugin
Homepage: http://www.thoughtbot.com/projects/paperclip
Clone URL: git://github.com/thoughtbot/paperclip.git
paperclip / tasks / paperclip_tasks.rake
100644 76 lines (68 sloc) 2.273 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def obtain_class
  class_name = ENV['CLASS'] || ENV['class']
  raise "Must specify CLASS" unless class_name
  @klass = Object.const_get(class_name)
end
 
def obtain_attachments
  name = ENV['ATTACHMENT'] || ENV['attachment']
  raise "Class #{@klass.name} has no attachments specified" unless @klass.respond_to?(:attachment_definitions)
  if !name.blank? && @klass.attachment_definitions.keys.include?(name)
    [ name ]
  else
    @klass.attachment_definitions.keys
  end
end
 
def for_all_attachments
  klass = obtain_class
  names = obtain_attachments
  ids = klass.connection.select_values("SELECT id FROM #{klass.table_name}")
 
  ids.each do |id|
    instance = klass.find(id)
    names.each do |name|
      result = if instance.send("#{ name }?")
                 yield(instance, name)
               else
                 true
               end
      print result ? "." : "x"; $stdout.flush
    end
  end
  puts " Done."
end
 
namespace :paperclip do
  desc "Refreshes both metadata and thumbnails."
  task :refresh => ["paperclip:refresh:metadata", "paperclip:refresh:thumbnails"]
 
  namespace :refresh do
    desc "Regenerates thumbnails for a given CLASS (and optional ATTACHMENT)."
    task :thumbnails => :environment do
      for_all_attachments do |instance, name|
        instance.send(name).reprocess!
      end
    end
 
    desc "Regenerates content_type/size metadata for a given CLASS (and optional ATTACHMENT)."
    task :metadata => :environment do
      for_all_attachments do |instance, name|
        if file = instance.send(name).to_file
          instance.send("#{name}_file_name=", instance.send("#{name}_file_name").strip)
          instance.send("#{name}_content_type=", file.content_type.strip)
          instance.send("#{name}_file_size=", file.size) if instance.respond_to?("#{name}_file_size")
          instance.save(false)
        else
          true
        end
      end
    end
  end
 
  desc "Cleans out invalid attachments. Useful after you've added new validations."
  task :clean => :environment do
    for_all_attachments do |instance, name|
      instance.send(name).send(:validate)
      if instance.send(name).valid?
        true
      else
        instance.send("#{name}=", nil)
        instance.save
      end
    end
  end
end