ariejan (owner)

Revisions

gist: 62025 Download_button fork
public
Description:
Easily update generated thumbnails for file_column
Public Clone URL: git://gist.github.com/62025.git
Embed All Files: show embed
image_updater.rb #
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
# recreates all file_column images in all needed sizes
class ImageUpdater
  
  def update_all
    update_model(:video, :image)
    update_model(:photo, :image)
  end
 
  private
 
  def update_model(class_name, attribute_name)
    eval(class_name.to_s.capitalize).find(:all).each {|instance|
      begin
        dir = instance.send(attribute_name)
        unless dir.blank?
          instance.send("#{attribute_name}=", upload(dir))
          instance.save!
        end
      rescue Exception => e
        puts e.message
      end
    }
  end
  
  # copied from file_column/test_case.rb
  def upload(path, content_type=:guess, type=:tempfile)
    if content_type == :guess
      case path
        when /\.jpg$/ then content_type = "image/jpeg"
        when /\.png$/ then content_type = "image/png"
        else content_type = nil
      end
    end
    uploaded_file(path, content_type, File.basename(path), type)
  end
    
  def uploaded_file(path, content_type, filename, type=:tempfile) # :nodoc:
    if type == :tempfile
      t = Tempfile.new(File.basename(filename))
      FileUtils.copy_file(path, t.path)
    else
      if path
        t = StringIO.new(IO.read(path))
      else
        t = StringIO.new
      end
    end
    (class << t; self; end).class_eval do
      alias local_path path if type == :tempfile
      define_method(:local_path) { "" } if type == :stringio
      define_method(:original_filename) {filename}
      define_method(:content_type) {content_type}
    end
    return t
  end
    
end