Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Work < ActiveRecord::Base
- belongs_to :medium
- validates_presence_of :filename, :message => "is blank, indicating that no file was selected to be uploaded."
- validates_uniqueness_of :filename, :message => "already exists, try uploading another file or deleting first."
- validates_format_of :pagenumber, :with => /\d+[A-Za-z]+?/, :allow_nil => true, :message => 'must be digits followed by letters.'
- def before_validation
- if self.title.nil? || self.title.empty?
- self.title = 'Untitled'
- end
- if self.pagenumber == ''
- self.pagenumber = nil
- end
- if self.size.nil? || self.title.empty?
- self.size = nil
- end
- end
- def file=(uploaded_file)
- @uploaded_file = uploaded_file
- fn=self.filename=sanitize_filename(File.basename(@uploaded_file.path))
- fn = fn.to_s if File.exists?(self.path_to_tempfile)
- fn = fn.split('_')
- fn.pop
- self.filename = fn.join('_')
- end
- def before_create
- require 'ImageUpload'
- File.open(self.path_to_tempfile, "w") { |f| f.write(@uploaded_file.read) }
- full = ImageUpload::upload_image(self.path_to_tempfile, self.filename, 'full', 'exhibition', 720, 600)
- medium = ImageUpload::upload_image(self.path_to_tempfile, self.filename, 'med', 'exhibition', 600, 500)
- thumb = ImageUpload::upload_image(self.path_to_tempfile, self.filename, 'thumb', 'exhibition', 200, 167)
- File.delete(self.path_to_tempfile)
- end
- def before_destroy
- # delete the file from the filesystem
- File.delete self.path_to_images + self.filename + '_full.jpg'
- File.delete self.path_to_images + self.filename + '_med.jpg'
- File.delete self.path_to_images + self.filename + '_thumb.jpg'
- end
- protected
- def sanitize_filename(value)
- just_filename = value.gsub(/^.*(\\|\/)/, '')
- just_filename.gsub(/[\W]/,'_')
- end
- def path_to_tempfile
- RAILS_ROOT + '/public/images/exhibition/' + self.filename + '_temp.jpg'
- end
- def path_to_images
- RAILS_ROOT + '/public/images/exhibition/'
- end
- end
- class ImageUpload
- def ImageUpload.upload_image(uploaded_file, filename, imagetype, category, maxwidth = 10000, maxheight = 100000)
- require 'RMagick'
- aspectratio = maxwidth.to_f / maxheight.to_f
- #pic = Magick::Image.read(imgfile).first
- pic = Magick::Image.read(uploaded_file).first
- imgwidth = pic.columns
- imgheight = pic.rows
- if (imgwidth > maxwidth) || (imgheight > maxheight)
- imgratio = imgwidth.to_f / imgheight.to_f
- imgratio > aspectratio ? scaleratio = maxwidth.to_f / imgwidth : scaleratio = maxheight.to_f / imgheight
- pic.thumbnail!(scaleratio)
- end
- pic.write(RAILS_ROOT + "/public/images/" + category + '/' + filename + '_' + imagetype + '.jpg')
- end
- end
Add Comment
Please, Sign In to add comment