thoughtbot-paperclip 2.1.5

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,321 @@
1
+ module Paperclip
2
+ # The Attachment class manages the files for a given attachment. It saves when the model saves,
3
+ # deletes when the model is destroyed, and processes the file upon assignment.
4
+ class Attachment
5
+
6
+ def self.default_options
7
+ @default_options ||= {
8
+ :url => "/:attachment/:id/:style/:basename.:extension",
9
+ :path => ":rails_root/public/:attachment/:id/:style/:basename.:extension",
10
+ :styles => {},
11
+ :default_url => "/:attachment/:style/missing.png",
12
+ :default_style => :original,
13
+ :validations => {},
14
+ :storage => :filesystem
15
+ }
16
+ end
17
+
18
+ attr_reader :name, :instance, :styles, :default_style, :convert_options
19
+
20
+ # Creates an Attachment object. +name+ is the name of the attachment, +instance+ is the
21
+ # ActiveRecord object instance it's attached to, and +options+ is the same as the hash
22
+ # passed to +has_attached_file+.
23
+ def initialize name, instance, options = {}
24
+ @name = name
25
+ @instance = instance
26
+
27
+ options = self.class.default_options.merge(options)
28
+
29
+ @url = options[:url]
30
+ @path = options[:path]
31
+ @styles = options[:styles]
32
+ @default_url = options[:default_url]
33
+ @validations = options[:validations]
34
+ @default_style = options[:default_style]
35
+ @storage = options[:storage]
36
+ @whiny_thumbnails = options[:whiny_thumbnails]
37
+ @convert_options = options[:convert_options] || {}
38
+ @options = options
39
+ @queued_for_delete = []
40
+ @queued_for_write = {}
41
+ @errors = {}
42
+ @validation_errors = nil
43
+ @dirty = false
44
+
45
+ normalize_style_definition
46
+ initialize_storage
47
+
48
+ logger.info("[paperclip] Paperclip attachment #{name} on #{instance.class} initialized.")
49
+ end
50
+
51
+ # What gets called when you call instance.attachment = File. It clears errors,
52
+ # assigns attributes, processes the file, and runs validations. It also queues up
53
+ # the previous file for deletion, to be flushed away on #save of its host.
54
+ # In addition to form uploads, you can also assign another Paperclip attachment:
55
+ # new_user.avatar = old_user.avatar
56
+ def assign uploaded_file
57
+ %w(file_name).each do |field|
58
+ unless @instance.class.column_names.include?("#{name}_#{field}")
59
+ raise PaperclipError.new("#{@instance.class} model does not have required column '#{name}_#{field}'")
60
+ end
61
+ end
62
+
63
+ if uploaded_file.is_a?(Paperclip::Attachment)
64
+ uploaded_file = uploaded_file.to_file(:original)
65
+ end
66
+
67
+ return nil unless valid_assignment?(uploaded_file)
68
+ logger.info("[paperclip] Assigning #{uploaded_file.inspect} to #{name}")
69
+
70
+ uploaded_file.binmode if uploaded_file.respond_to? :binmode
71
+ queue_existing_for_delete
72
+ @errors = {}
73
+ @validation_errors = nil
74
+
75
+ return nil if uploaded_file.nil?
76
+
77
+ logger.info("[paperclip] Writing attributes for #{name}")
78
+ @queued_for_write[:original] = uploaded_file.to_tempfile
79
+ instance_write(:file_name, uploaded_file.original_filename.strip.gsub(/[^\w\d\.\-]+/, '_'))
80
+ instance_write(:content_type, uploaded_file.content_type.to_s.strip)
81
+ instance_write(:file_size, uploaded_file.size.to_i)
82
+ instance_write(:updated_at, Time.now)
83
+
84
+ @dirty = true
85
+
86
+ post_process
87
+
88
+ # Reset the file size if the original file was reprocessed.
89
+ instance_write(:file_size, uploaded_file.size.to_i)
90
+ ensure
91
+ validate
92
+ end
93
+
94
+ # Returns the public URL of the attachment, with a given style. Note that this
95
+ # does not necessarily need to point to a file that your web server can access
96
+ # and can point to an action in your app, if you need fine grained security.
97
+ # This is not recommended if you don't need the security, however, for
98
+ # performance reasons.
99
+ def url style = default_style
100
+ url = original_filename.nil? ? interpolate(@default_url, style) : interpolate(@url, style)
101
+ updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url
102
+ end
103
+
104
+ # Returns the path of the attachment as defined by the :path option. If the
105
+ # file is stored in the filesystem the path refers to the path of the file on
106
+ # disk. If the file is stored in S3, the path is the "key" part of the URL,
107
+ # and the :bucket option refers to the S3 bucket.
108
+ def path style = nil #:nodoc:
109
+ original_filename.nil? ? nil : interpolate(@path, style)
110
+ end
111
+
112
+ # Alias to +url+
113
+ def to_s style = nil
114
+ url(style)
115
+ end
116
+
117
+ # Returns true if there are no errors on this attachment.
118
+ def valid?
119
+ validate
120
+ errors.empty?
121
+ end
122
+
123
+ # Returns an array containing the errors on this attachment.
124
+ def errors
125
+ @errors
126
+ end
127
+
128
+ # Returns true if there are changes that need to be saved.
129
+ def dirty?
130
+ @dirty
131
+ end
132
+
133
+ # Saves the file, if there are no errors. If there are, it flushes them to
134
+ # the instance's errors and returns false, cancelling the save.
135
+ def save
136
+ if valid?
137
+ logger.info("[paperclip] Saving files for #{name}")
138
+ flush_deletes
139
+ flush_writes
140
+ @dirty = false
141
+ true
142
+ else
143
+ logger.info("[paperclip] Errors on #{name}. Not saving.")
144
+ flush_errors
145
+ false
146
+ end
147
+ end
148
+
149
+ # Returns the name of the file as originally assigned, and as lives in the
150
+ # <attachment>_file_name attribute of the model.
151
+ def original_filename
152
+ instance_read(:file_name)
153
+ end
154
+
155
+ def size
156
+ instance_read(:file_size) || (@queued_for_write[:original] && @queued_for_write[:original].size)
157
+ end
158
+
159
+ def content_type
160
+ instance_read(:content_type)
161
+ end
162
+
163
+ def updated_at
164
+ time = instance_read(:updated_at)
165
+ time && time.to_i
166
+ end
167
+
168
+ # A hash of procs that are run during the interpolation of a path or url.
169
+ # A variable of the format :name will be replaced with the return value of
170
+ # the proc named ":name". Each lambda takes the attachment and the current
171
+ # style as arguments. This hash can be added to with your own proc if
172
+ # necessary.
173
+ def self.interpolations
174
+ @interpolations ||= {
175
+ :rails_root => lambda{|attachment,style| RAILS_ROOT },
176
+ :rails_env => lambda{|attachment,style| RAILS_ENV },
177
+ :class => lambda do |attachment,style|
178
+ attachment.instance.class.name.underscore.pluralize
179
+ end,
180
+ :basename => lambda do |attachment,style|
181
+ attachment.original_filename.gsub(/#{File.extname(attachment.original_filename)}$/, "")
182
+ end,
183
+ :extension => lambda do |attachment,style|
184
+ ((style = attachment.styles[style]) && style.last) ||
185
+ File.extname(attachment.original_filename).gsub(/^\.+/, "")
186
+ end,
187
+ :id => lambda{|attachment,style| attachment.instance.id },
188
+ :id_partition => lambda do |attachment, style|
189
+ ("%09d" % attachment.instance.id).scan(/\d{3}/).join("/")
190
+ end,
191
+ :attachment => lambda{|attachment,style| attachment.name.to_s.downcase.pluralize },
192
+ :style => lambda{|attachment,style| style || attachment.default_style },
193
+ }
194
+ end
195
+
196
+ # This method really shouldn't be called that often. It's expected use is in the
197
+ # paperclip:refresh rake task and that's it. It will regenerate all thumbnails
198
+ # forcefully, by reobtaining the original file and going through the post-process
199
+ # again.
200
+ def reprocess!
201
+ new_original = Tempfile.new("paperclip-reprocess")
202
+ if old_original = to_file(:original)
203
+ new_original.write( old_original.read )
204
+ new_original.rewind
205
+
206
+ @queued_for_write = { :original => new_original }
207
+ post_process
208
+
209
+ old_original.close if old_original.respond_to?(:close)
210
+
211
+ save
212
+ else
213
+ true
214
+ end
215
+ end
216
+
217
+ def file?
218
+ !original_filename.blank?
219
+ end
220
+
221
+ def instance_write(attr, value)
222
+ setter = :"#{name}_#{attr}="
223
+ responds = instance.respond_to?(setter)
224
+ instance.send(setter, value) if responds || attr.to_s == "file_name"
225
+ end
226
+
227
+ def instance_read(attr)
228
+ getter = :"#{name}_#{attr}"
229
+ responds = instance.respond_to?(getter)
230
+ instance.send(getter) if responds || attr.to_s == "file_name"
231
+ end
232
+
233
+ private
234
+
235
+ def logger
236
+ instance.logger
237
+ end
238
+
239
+ def valid_assignment? file #:nodoc:
240
+ file.nil? || (file.respond_to?(:original_filename) && file.respond_to?(:content_type))
241
+ end
242
+
243
+ def validate #:nodoc:
244
+ unless @validation_errors
245
+ @validation_errors = @validations.inject({}) do |errors, validation|
246
+ name, block = validation
247
+ errors[name] = block.call(self, instance) if block
248
+ errors
249
+ end
250
+ @validation_errors.reject!{|k,v| v == nil }
251
+ @errors.merge!(@validation_errors)
252
+ end
253
+ @validation_errors
254
+ end
255
+
256
+ def normalize_style_definition
257
+ @styles.each do |name, args|
258
+ dimensions, format = [args, nil].flatten[0..1]
259
+ format = nil if format == ""
260
+ @styles[name] = [dimensions, format]
261
+ end
262
+ end
263
+
264
+ def initialize_storage
265
+ @storage_module = Paperclip::Storage.const_get(@storage.to_s.capitalize)
266
+ self.extend(@storage_module)
267
+ end
268
+
269
+ def extra_options_for(style) #:nodoc:
270
+ [ convert_options[style], convert_options[:all] ].compact.join(" ")
271
+ end
272
+
273
+ def post_process #:nodoc:
274
+ return if @queued_for_write[:original].nil?
275
+ logger.info("[paperclip] Post-processing #{name}")
276
+ @styles.each do |name, args|
277
+ begin
278
+ dimensions, format = args
279
+ dimensions = dimensions.call(instance) if dimensions.respond_to? :call
280
+ @queued_for_write[name] = Thumbnail.make(@queued_for_write[:original],
281
+ dimensions,
282
+ format,
283
+ extra_options_for(name),
284
+ @whiny_thumbnails)
285
+ rescue PaperclipError => e
286
+ (@errors[:processing] ||= []) << e.message if @whiny_thumbnails
287
+ end
288
+ end
289
+ end
290
+
291
+ def interpolate pattern, style = default_style #:nodoc:
292
+ interpolations = self.class.interpolations.sort{|a,b| a.first.to_s <=> b.first.to_s }
293
+ interpolations.reverse.inject( pattern.dup ) do |result, interpolation|
294
+ tag, blk = interpolation
295
+ result.gsub(/:#{tag}/) do |match|
296
+ blk.call( self, style )
297
+ end
298
+ end
299
+ end
300
+
301
+ def queue_existing_for_delete #:nodoc:
302
+ return unless file?
303
+ logger.info("[paperclip] Queueing the existing files for #{name} for deletion.")
304
+ @queued_for_delete += [:original, *@styles.keys].uniq.map do |style|
305
+ path(style) if exists?(style)
306
+ end.compact
307
+ instance_write(:file_name, nil)
308
+ instance_write(:content_type, nil)
309
+ instance_write(:file_size, nil)
310
+ instance_write(:updated_at, nil)
311
+ end
312
+
313
+ def flush_errors #:nodoc:
314
+ @errors.each do |error, message|
315
+ instance.errors.add(name, message) if message
316
+ end
317
+ end
318
+
319
+ end
320
+ end
321
+
@@ -0,0 +1,115 @@
1
+ module Paperclip
2
+
3
+ # Defines the geometry of an image.
4
+ class Geometry
5
+ attr_accessor :height, :width, :modifier
6
+
7
+ # Gives a Geometry representing the given height and width
8
+ def initialize width = nil, height = nil, modifier = nil
9
+ @height = height.to_f
10
+ @width = width.to_f
11
+ @modifier = modifier
12
+ end
13
+
14
+ # Uses ImageMagick to determing the dimensions of a file, passed in as either a
15
+ # File or path.
16
+ def self.from_file file
17
+ file = file.path if file.respond_to? "path"
18
+ geometry = begin
19
+ Paperclip.run("identify", %Q[-format "%wx%h" "#{file}"])
20
+ rescue PaperclipCommandLineError
21
+ ""
22
+ end
23
+ parse(geometry) ||
24
+ raise(NotIdentifiedByImageMagickError.new("#{file} is not recognized by the 'identify' command."))
25
+ end
26
+
27
+ # Parses a "WxH" formatted string, where W is the width and H is the height.
28
+ def self.parse string
29
+ if match = (string && string.match(/\b(\d*)x?(\d*)\b([\>\<\#\@\%^!])?/))
30
+ Geometry.new(*match[1,3])
31
+ end
32
+ end
33
+
34
+ # True if the dimensions represent a square
35
+ def square?
36
+ height == width
37
+ end
38
+
39
+ # True if the dimensions represent a horizontal rectangle
40
+ def horizontal?
41
+ height < width
42
+ end
43
+
44
+ # True if the dimensions represent a vertical rectangle
45
+ def vertical?
46
+ height > width
47
+ end
48
+
49
+ # The aspect ratio of the dimensions.
50
+ def aspect
51
+ width / height
52
+ end
53
+
54
+ # Returns the larger of the two dimensions
55
+ def larger
56
+ [height, width].max
57
+ end
58
+
59
+ # Returns the smaller of the two dimensions
60
+ def smaller
61
+ [height, width].min
62
+ end
63
+
64
+ # Returns the width and height in a format suitable to be passed to Geometry.parse
65
+ def to_s
66
+ s = ""
67
+ s << width.to_i.to_s if width > 0
68
+ s << "x#{height.to_i}" if height > 0
69
+ s << modifier.to_s
70
+ s
71
+ end
72
+
73
+ # Same as to_s
74
+ def inspect
75
+ to_s
76
+ end
77
+
78
+ # Returns the scaling and cropping geometries (in string-based ImageMagick format)
79
+ # neccessary to transform this Geometry into the Geometry given. If crop is true,
80
+ # then it is assumed the destination Geometry will be the exact final resolution.
81
+ # In this case, the source Geometry is scaled so that an image containing the
82
+ # destination Geometry would be completely filled by the source image, and any
83
+ # overhanging image would be cropped. Useful for square thumbnail images. The cropping
84
+ # is weighted at the center of the Geometry.
85
+ def transformation_to dst, crop = false
86
+ if crop
87
+ ratio = Geometry.new( dst.width / self.width, dst.height / self.height )
88
+ scale_geometry, scale = scaling(dst, ratio)
89
+ crop_geometry = cropping(dst, ratio, scale)
90
+ else
91
+ scale_geometry = dst.to_s
92
+ end
93
+
94
+ [ scale_geometry, crop_geometry ]
95
+ end
96
+
97
+ private
98
+
99
+ def scaling dst, ratio
100
+ if ratio.horizontal? || ratio.square?
101
+ [ "%dx" % dst.width, ratio.width ]
102
+ else
103
+ [ "x%d" % dst.height, ratio.height ]
104
+ end
105
+ end
106
+
107
+ def cropping dst, ratio, scale
108
+ if ratio.horizontal? || ratio.square?
109
+ "%dx%d+%d+%d" % [ dst.width, dst.height, 0, (self.height * scale - dst.height) / 2 ]
110
+ else
111
+ "%dx%d+%d+%d" % [ dst.width, dst.height, (self.width * scale - dst.width) / 2, 0 ]
112
+ end
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,58 @@
1
+ # Provides method that can be included on File-type objects (IO, StringIO, Tempfile, etc) to allow stream copying
2
+ # and Tempfile conversion.
3
+ module IOStream
4
+
5
+ # Returns a Tempfile containing the contents of the readable object.
6
+ def to_tempfile
7
+ tempfile = Tempfile.new("stream")
8
+ tempfile.binmode
9
+ self.stream_to(tempfile)
10
+ end
11
+
12
+ # Copies one read-able object from one place to another in blocks, obviating the need to load
13
+ # the whole thing into memory. Defaults to 8k blocks. If this module is included in both
14
+ # StringIO and Tempfile, then either can have its data copied anywhere else without typing
15
+ # worries or memory overhead worries. Returns a File if a String is passed in as the destination
16
+ # and returns the IO or Tempfile as passed in if one is sent as the destination.
17
+ def stream_to path_or_file, in_blocks_of = 8192
18
+ dstio = case path_or_file
19
+ when String then File.new(path_or_file, "wb+")
20
+ when IO then path_or_file
21
+ when Tempfile then path_or_file
22
+ end
23
+ buffer = ""
24
+ self.rewind
25
+ while self.read(in_blocks_of, buffer) do
26
+ dstio.write(buffer)
27
+ end
28
+ dstio.rewind
29
+ dstio
30
+ end
31
+ end
32
+
33
+ class IO
34
+ include IOStream
35
+ end
36
+
37
+ %w( Tempfile StringIO ).each do |klass|
38
+ if Object.const_defined? klass
39
+ Object.const_get(klass).class_eval do
40
+ include IOStream
41
+ end
42
+ end
43
+ end
44
+
45
+ # Corrects a bug in Windows when asking for Tempfile size.
46
+ if defined? Tempfile
47
+ class Tempfile
48
+ def size
49
+ if @tmpfile
50
+ @tmpfile.fsync
51
+ @tmpfile.flush
52
+ @tmpfile.stat.size
53
+ else
54
+ 0
55
+ end
56
+ end
57
+ end
58
+ end