My favorites
▼
|
Sign in
substruct
Open-source Ruby on Rails E-Commerce
Project Home
Downloads
Wiki
Issues
Source
READ-ONLY: This project has been
archived
. For more information see
this post
.
Search
Search within:
All issues
Open issues
New issues
Issues to verify
for
Advanced search
Search tips
Subscriptions
Issue
25
attachment: 001_update_images.rb
(2.6 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
# Reprocess all the images, updating images sizes as the UI has changed.
#
class UpdateImages < ActiveRecord::Migration
def self.up
# Images will be temporarily stored here.
mkdir_p File.join(RAILS_ROOT, 'tmp', 'images')
# For each product.
Product.find(:all).each do |a_product|
# Open a transaction for each product, if something goes wrong here, the images
# references will still be there, but the image files will be in tmp.
ActiveRecord::Base.transaction do
temp_array = []
# Copy each image to tmp, erase it and store its path, type and rank in an array.
a_product.images.each do |an_image|
FileUtils.cp(an_image.full_filename, File.join(RAILS_ROOT, 'tmp'))
a_product_image = ProductImage.find(
:first, :conditions => ["image_id = ? AND product_id = ?", an_image.id, a_product.id]
)
temp_array << [
File.join(RAILS_ROOT, 'tmp', an_image.filename),
an_image.content_type,
a_product_image.rank
]
an_image.destroy
end
# Upload each image copied to tmp back to the product and erase it from tmp.
temp_array.each do |an_element|
say "Processing #{an_element[0]}, #{an_element[1]}, #{an_element[2]}"
an_upload = UpdateImages.uploaded_file(an_element[0], an_element[1])
new_image = Image.new
new_image.uploaded_data = an_upload
if new_image.save
a_product.images << new_image
# Update the rank if it have a rank.
if an_element[2]
a_product_image = ProductImage.find(
:first, :conditions => ["image_id = ? AND product_id = ?", new_image.id, a_product.id]
)
a_product_image.rank = an_element[2]
a_product_image.save
end
rm_rf an_element[0]
else
puts new_image.errors.full_messages
end
end
end # Transaction
end # Product.each
rm_rf File.join(RAILS_ROOT, 'tmp', 'images')
end
def self.down
up
end
# Define the method to create an upload file and dont depend of anything else.
def self.uploaded_file(path, content_type = Mime::TEXT, binary = false)
filename ||= File.basename(path)
t = Tempfile.new(filename)
FileUtils.copy_file(path, t.path)
(class << t; self; end;).class_eval do
alias local_path path
define_method(:original_filename) { filename }
define_method(:content_type) { content_type }
end
return t
end
end
Powered by
Google Project Hosting