We are a software consultancy based in Berlin, Germany. We deliver
high quality web apps in short timespans.

Upstream Agile GmbH

FileColumn: regenerate images

August 12, 2007 by alex

If you change the images dimensions or introduce a new version for models using file column you need a way to update the existing ones. Here is a script that will regenerate all file column images and its version. We still look for a way to generate only new versions.

# recreates all file_column images in all needed sizes

class ImageUpdater

  def update_all
    update_model(:user, :photo)
    update_model(:auto, :photo)
    update_model(:photo, :file)
    update_model(:group, :photo)
  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