require 'RMagick'  # or, this line can go in environment.rb
include Magick

class Photo < ActiveRecord::Base
  belongs_to :item

  def photo=(image_field)

    self.name = base_part_of(image_field.original_filename)
    self.content_type = image_field.content_type.chomp

    img = Magick::Image::read_inline(Base64.b64encode(image_field.read)).first
    img_tn = img

    img.change_geometry!('600x600') do |cols, rows, image|
      if cols < img.columns  or rows < img.rows then
        image.resize!(cols, rows)
      end     
    end     
    self.data = img.to_blob

    img_tn.change_geometry!('100x100') do |cols, rows, image|
      if cols < img.columns  or rows < img.rows then
        image.resize!(cols, rows)
      end     
    end     
    self.thumb = img_tn.to_blob

    # Envoke RMagick Garbage Collection:
    GC.start
  end

  def base_part_of(file_name)
    name = File.basename(file_name)
    name.gsub(/[^\w._-]/, '')
  end
end