lostboy-paperclip 2.2.6.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (44) hide show
  1. data/LICENSE +26 -0
  2. data/README.rdoc +172 -0
  3. data/Rakefile +77 -0
  4. data/generators/paperclip/USAGE +5 -0
  5. data/generators/paperclip/paperclip_generator.rb +27 -0
  6. data/generators/paperclip/templates/paperclip_migration.rb.erb +19 -0
  7. data/init.rb +1 -0
  8. data/lib/paperclip/attachment.rb +398 -0
  9. data/lib/paperclip/callback_compatability.rb +33 -0
  10. data/lib/paperclip/geometry.rb +115 -0
  11. data/lib/paperclip/iostream.rb +58 -0
  12. data/lib/paperclip/matchers/have_attached_file_matcher.rb +49 -0
  13. data/lib/paperclip/matchers/validate_attachment_content_type_matcher.rb +66 -0
  14. data/lib/paperclip/matchers/validate_attachment_presence_matcher.rb +48 -0
  15. data/lib/paperclip/matchers/validate_attachment_size_matcher.rb +83 -0
  16. data/lib/paperclip/matchers.rb +4 -0
  17. data/lib/paperclip/processor.rb +48 -0
  18. data/lib/paperclip/storage.rb +241 -0
  19. data/lib/paperclip/thumbnail.rb +70 -0
  20. data/lib/paperclip/upfile.rb +48 -0
  21. data/lib/paperclip.rb +318 -0
  22. data/shoulda_macros/paperclip.rb +68 -0
  23. data/tasks/paperclip_tasks.rake +79 -0
  24. data/test/attachment_test.rb +723 -0
  25. data/test/database.yml +4 -0
  26. data/test/fixtures/12k.png +0 -0
  27. data/test/fixtures/50x50.png +0 -0
  28. data/test/fixtures/5k.png +0 -0
  29. data/test/fixtures/bad.png +1 -0
  30. data/test/fixtures/text.txt +0 -0
  31. data/test/fixtures/twopage.pdf +0 -0
  32. data/test/geometry_test.rb +168 -0
  33. data/test/helper.rb +82 -0
  34. data/test/integration_test.rb +495 -0
  35. data/test/iostream_test.rb +71 -0
  36. data/test/matchers/have_attached_file_matcher_test.rb +21 -0
  37. data/test/matchers/validate_attachment_content_type_matcher_test.rb +30 -0
  38. data/test/matchers/validate_attachment_presence_matcher_test.rb +21 -0
  39. data/test/matchers/validate_attachment_size_matcher_test.rb +50 -0
  40. data/test/paperclip_test.rb +237 -0
  41. data/test/processor_test.rb +10 -0
  42. data/test/storage_test.rb +277 -0
  43. data/test/thumbnail_test.rb +177 -0
  44. metadata +133 -0
@@ -0,0 +1,398 @@
1
+ module Paperclip
2
+ # The Attachment class manages the files for a given attachment. It saves
3
+ # when the model saves, deletes when the model is destroyed, and processes
4
+ # the file upon assignment.
5
+ class Attachment
6
+
7
+ def self.default_options
8
+ @default_options ||= {
9
+ :url => "/system/:attachment/:id/:style/:basename.:extension",
10
+ :path => ":rails_root/public/system/:attachment/:id/:style/:basename.:extension",
11
+ :styles => {},
12
+ :default_url => "/:attachment/:style/missing.png",
13
+ :default_style => :original,
14
+ :validations => {},
15
+ :storage => :filesystem
16
+ }
17
+ end
18
+
19
+ attr_reader :name, :instance, :styles, :default_style, :convert_options, :queued_for_write
20
+
21
+ # Creates an Attachment object. +name+ is the name of the attachment,
22
+ # +instance+ is the ActiveRecord object instance it's attached to, and
23
+ # +options+ is the same as the hash passed to +has_attached_file+.
24
+ def initialize name, instance, options = {}
25
+ @name = name
26
+ @instance = instance
27
+
28
+ options = self.class.default_options.merge(options)
29
+
30
+ @url = options[:url]
31
+ @url = @url.call(self) if @url.is_a?(Proc)
32
+ @path = options[:path]
33
+ @path = @path.call(self) if @path.is_a?(Proc)
34
+ @styles = options[:styles]
35
+ @styles = @styles.call(self) if @styles.is_a?(Proc)
36
+ @default_url = options[:default_url]
37
+ @validations = options[:validations]
38
+ @default_style = options[:default_style]
39
+ @storage = options[:storage]
40
+ @whiny = options[:whiny_thumbnails]
41
+ @convert_options = options[:convert_options] || {}
42
+ @processors = options[:processors] || [:thumbnail]
43
+ @options = options
44
+ @queued_for_delete = []
45
+ @queued_for_write = {}
46
+ @errors = {}
47
+ @validation_errors = nil
48
+ @dirty = false
49
+
50
+ normalize_style_definition
51
+ initialize_storage
52
+
53
+ log("Paperclip attachment #{name} on #{instance.class} initialized.")
54
+ end
55
+
56
+ # What gets called when you call instance.attachment = File. It clears
57
+ # errors, assigns attributes, processes the file, and runs validations. It
58
+ # also queues up the previous file for deletion, to be flushed away on
59
+ # #save of its host. In addition to form uploads, you can also assign
60
+ # another Paperclip attachment:
61
+ # new_user.avatar = old_user.avatar
62
+ # If the file that is assigned is not valid, the processing (i.e.
63
+ # thumbnailing, etc) will NOT be run.
64
+ def assign uploaded_file
65
+ %w(file_name).each do |field|
66
+ unless @instance.class.column_names.include?("#{name}_#{field}")
67
+ raise PaperclipError.new("#{@instance.class} model does not have required column '#{name}_#{field}'")
68
+ end
69
+ end
70
+
71
+ if uploaded_file.is_a?(Paperclip::Attachment)
72
+ uploaded_file = uploaded_file.to_file(:original)
73
+ close_uploaded_file = uploaded_file.respond_to?(:close)
74
+ end
75
+
76
+ return nil unless valid_assignment?(uploaded_file)
77
+ log("Assigning #{uploaded_file.inspect} to #{name}")
78
+
79
+ uploaded_file.binmode if uploaded_file.respond_to? :binmode
80
+ queue_existing_for_delete
81
+ @errors = {}
82
+ @validation_errors = nil
83
+
84
+ return nil if uploaded_file.nil?
85
+
86
+ log("Writing attributes for #{name}")
87
+ @queued_for_write[:original] = uploaded_file.to_tempfile
88
+ instance_write(:file_name, uploaded_file.original_filename.strip.gsub(/[^\w\d\.\-]+/, '_'))
89
+ instance_write(:content_type, uploaded_file.content_type.to_s.strip)
90
+ instance_write(:file_size, uploaded_file.size.to_i)
91
+ instance_write(:updated_at, Time.now)
92
+
93
+ @dirty = true
94
+
95
+ post_process if valid?
96
+
97
+ # Reset the file size if the original file was reprocessed.
98
+ instance_write(:file_size, @queued_for_write[:original].size.to_i)
99
+ ensure
100
+ uploaded_file.close if close_uploaded_file
101
+ validate
102
+ end
103
+
104
+ # Returns the public URL of the attachment, with a given style. Note that
105
+ # this does not necessarily need to point to a file that your web server
106
+ # can access and can point to an action in your app, if you need fine
107
+ # grained security. This is not recommended if you don't need the
108
+ # security, however, for performance reasons. set
109
+ # include_updated_timestamp to false if you want to stop the attachment
110
+ # update time appended to the url
111
+ def url style = default_style, include_updated_timestamp = true
112
+ url = original_filename.nil? ? interpolate(@default_url, style) : interpolate(@url, style)
113
+ include_updated_timestamp && updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url
114
+ end
115
+
116
+ # Returns the path of the attachment as defined by the :path option. If the
117
+ # file is stored in the filesystem the path refers to the path of the file
118
+ # on disk. If the file is stored in S3, the path is the "key" part of the
119
+ # URL, and the :bucket option refers to the S3 bucket.
120
+ def path style = nil #:nodoc:
121
+ original_filename.nil? ? nil : interpolate(@path, style)
122
+ end
123
+
124
+ # Alias to +url+
125
+ def to_s style = nil
126
+ url(style)
127
+ end
128
+
129
+ # Returns true if there are no errors on this attachment.
130
+ def valid?
131
+ validate
132
+ errors.empty?
133
+ end
134
+
135
+ # Returns an array containing the errors on this attachment.
136
+ def errors
137
+ @errors
138
+ end
139
+
140
+ # Returns true if there are changes that need to be saved.
141
+ def dirty?
142
+ @dirty
143
+ end
144
+
145
+ # Saves the file, if there are no errors. If there are, it flushes them to
146
+ # the instance's errors and returns false, cancelling the save.
147
+ def save
148
+ if valid?
149
+ log("Saving files for #{name}")
150
+ flush_deletes
151
+ flush_writes
152
+ @dirty = false
153
+ true
154
+ else
155
+ log("Errors on #{name}. Not saving.")
156
+ flush_errors
157
+ false
158
+ end
159
+ end
160
+
161
+ # Returns the name of the file as originally assigned, and lives in the
162
+ # <attachment>_file_name attribute of the model.
163
+ def original_filename
164
+ instance_read(:file_name)
165
+ end
166
+
167
+ # Returns the size of the file as originally assigned, and lives in the
168
+ # <attachment>_file_size attribute of the model.
169
+ def size
170
+ instance_read(:file_size) || (@queued_for_write[:original] && @queued_for_write[:original].size)
171
+ end
172
+
173
+ # Returns the content_type of the file as originally assigned, and lives
174
+ # in the <attachment>_content_type attribute of the model.
175
+ def content_type
176
+ instance_read(:content_type)
177
+ end
178
+
179
+ # Returns the last modified time of the file as originally assigned, and
180
+ # lives in the <attachment>_updated_at attribute of the model.
181
+ def updated_at
182
+ time = instance_read(:updated_at)
183
+ time && time.to_i
184
+ end
185
+
186
+ # A hash of procs that are run during the interpolation of a path or url.
187
+ # A variable of the format :name will be replaced with the return value of
188
+ # the proc named ":name". Each lambda takes the attachment and the current
189
+ # style as arguments. This hash can be added to with your own proc if
190
+ # necessary.
191
+ def self.interpolations
192
+ @interpolations ||= {
193
+ :rails_root => lambda{|attachment,style| RAILS_ROOT },
194
+ :rails_env => lambda{|attachment,style| RAILS_ENV },
195
+ :class => lambda do |attachment,style|
196
+ attachment.instance.class.name.underscore.pluralize
197
+ end,
198
+ :basename => lambda do |attachment,style|
199
+ attachment.original_filename.gsub(/#{File.extname(attachment.original_filename)}$/, "")
200
+ end,
201
+ :extension => lambda do |attachment,style|
202
+ ((style = attachment.styles[style]) && style[:format]) ||
203
+ File.extname(attachment.original_filename).gsub(/^\.+/, "")
204
+ end,
205
+ :id => lambda{|attachment,style| attachment.instance.id },
206
+ :id_partition => lambda do |attachment, style|
207
+ ("%09d" % attachment.instance.id).scan(/\d{3}/).join("/")
208
+ end,
209
+ :attachment => lambda{|attachment,style| attachment.name.to_s.downcase.pluralize },
210
+ :style => lambda{|attachment,style| style || attachment.default_style },
211
+ }
212
+ end
213
+
214
+ # This method really shouldn't be called that often. It's expected use is
215
+ # in the paperclip:refresh rake task and that's it. It will regenerate all
216
+ # thumbnails forcefully, by reobtaining the original file and going through
217
+ # the post-process again.
218
+ def reprocess!
219
+ new_original = Tempfile.new("paperclip-reprocess")
220
+ new_original.binmode
221
+ if old_original = to_file(:original)
222
+ new_original.write( old_original.read )
223
+ new_original.rewind
224
+
225
+ @queued_for_write = { :original => new_original }
226
+ post_process
227
+
228
+ old_original.close if old_original.respond_to?(:close)
229
+
230
+ save
231
+ else
232
+ true
233
+ end
234
+ end
235
+
236
+ # Returns true if a file has been assigned.
237
+ def file?
238
+ !original_filename.blank?
239
+ end
240
+
241
+ # Writes the attachment-specific attribute on the instance. For example,
242
+ # instance_write(:file_name, "me.jpg") will write "me.jpg" to the instance's
243
+ # "avatar_file_name" field (assuming the attachment is called avatar).
244
+ def instance_write(attr, value)
245
+ setter = :"#{name}_#{attr}="
246
+ responds = instance.respond_to?(setter)
247
+ self.instance_variable_set("@_#{setter.to_s.chop}", value)
248
+ instance.send(setter, value) if responds || attr.to_s == "file_name"
249
+ end
250
+
251
+ # Reads the attachment-specific attribute on the instance. See instance_write
252
+ # for more details.
253
+ def instance_read(attr)
254
+ getter = :"#{name}_#{attr}"
255
+ responds = instance.respond_to?(getter)
256
+ cached = self.instance_variable_get("@_#{getter}")
257
+ return cached if cached
258
+ instance.send(getter) if responds || attr.to_s == "file_name"
259
+ end
260
+
261
+ private
262
+
263
+ def logger #:nodoc:
264
+ instance.logger
265
+ end
266
+
267
+ def log message #:nodoc:
268
+ logger.info("[paperclip] #{message}") if logging?
269
+ end
270
+
271
+ def logging? #:nodoc:
272
+ Paperclip.options[:log]
273
+ end
274
+
275
+ def valid_assignment? file #:nodoc:
276
+ file.nil? || (file.respond_to?(:original_filename) && file.respond_to?(:content_type))
277
+ end
278
+
279
+ def validate #:nodoc:
280
+ unless @validation_errors
281
+ @validation_errors = @validations.inject({}) do |errors, validation|
282
+ name, block = validation
283
+ errors[name] = block.call(self, instance) if block
284
+ errors
285
+ end
286
+ @validation_errors.reject!{|k,v| v == nil }
287
+ @errors.merge!(@validation_errors)
288
+ end
289
+ @validation_errors
290
+ end
291
+
292
+ def normalize_style_definition #:nodoc:
293
+ @styles.each do |name, args|
294
+ unless args.is_a? Hash
295
+ dimensions, format = [args, nil].flatten[0..1]
296
+ format = nil if format.blank?
297
+ @styles[name] = {
298
+ :processors => @processors,
299
+ :geometry => dimensions,
300
+ :format => format,
301
+ :whiny => @whiny,
302
+ :convert_options => extra_options_for(name)
303
+ }
304
+ else
305
+ @styles[name] = {
306
+ :processors => @processors,
307
+ :whiny => @whiny,
308
+ :convert_options => extra_options_for(name)
309
+ }.merge(@styles[name])
310
+ end
311
+ end
312
+ end
313
+
314
+ def solidify_style_definitions #:nodoc:
315
+ @styles.each do |name, args|
316
+ @styles[name][:geometry] = @styles[name][:geometry].call(instance) if @styles[name][:geometry].respond_to?(:call)
317
+ @styles[name][:processors] = @styles[name][:processors].call(instance) if @styles[name][:processors].respond_to?(:call)
318
+ end
319
+ end
320
+
321
+ def initialize_storage #:nodoc:
322
+ @storage_module = Paperclip::Storage.const_get(@storage.to_s.capitalize)
323
+ self.extend(@storage_module)
324
+ end
325
+
326
+ def extra_options_for(style) #:nodoc:
327
+ all_options = convert_options[:all]
328
+ all_options = all_options.call(instance) if all_options.respond_to?(:call)
329
+ style_options = convert_options[style]
330
+ style_options = style_options.call(instance) if style_options.respond_to?(:call)
331
+
332
+ [ style_options, all_options ].compact.join(" ")
333
+ end
334
+
335
+ def post_process #:nodoc:
336
+ return if @queued_for_write[:original].nil?
337
+ solidify_style_definitions
338
+ return if fire_events(:before)
339
+ post_process_styles
340
+ return if fire_events(:after)
341
+ end
342
+
343
+ def fire_events(which)
344
+ return true if callback(:"#{which}_post_process") == false
345
+ return true if callback(:"#{which}_#{name}_post_process") == false
346
+ end
347
+
348
+ def callback which #:nodoc:
349
+ instance.run_callbacks(which, @queued_for_write){|result, obj| result == false }
350
+ end
351
+
352
+ def post_process_styles
353
+ log("Post-processing #{name}")
354
+ @styles.each do |name, args|
355
+ begin
356
+ raise RuntimeError.new("Style #{name} has no processors defined.") if args[:processors].blank?
357
+ @queued_for_write[name] = args[:processors].inject(@queued_for_write[:original]) do |file, processor|
358
+ log("Processing #{name} #{file} in the #{processor} processor.")
359
+ Paperclip.processor(processor).make(file, args, self)
360
+ end
361
+ rescue PaperclipError => e
362
+ log("An error was received while processing: #{e.inspect}")
363
+ (@errors[:processing] ||= []) << e.message if @whiny
364
+ end
365
+ end
366
+ end
367
+
368
+ def interpolate pattern, style = default_style #:nodoc:
369
+ interpolations = self.class.interpolations.sort{|a,b| a.first.to_s <=> b.first.to_s }
370
+ interpolations.reverse.inject( pattern.dup ) do |result, interpolation|
371
+ tag, blk = interpolation
372
+ result.gsub(/:#{tag}/) do |match|
373
+ blk.call( self, style )
374
+ end
375
+ end
376
+ end
377
+
378
+ def queue_existing_for_delete #:nodoc:
379
+ return unless file?
380
+ log("Queueing the existing files for #{name} for deletion.")
381
+ @queued_for_delete += [:original, *@styles.keys].uniq.map do |style|
382
+ path(style) if exists?(style)
383
+ end.compact
384
+ instance_write(:file_name, nil)
385
+ instance_write(:content_type, nil)
386
+ instance_write(:file_size, nil)
387
+ instance_write(:updated_at, nil)
388
+ end
389
+
390
+ def flush_errors #:nodoc:
391
+ @errors.each do |error, message|
392
+ [message].flatten.each {|m| instance.errors.add(name, m) }
393
+ end
394
+ end
395
+
396
+ end
397
+ end
398
+
@@ -0,0 +1,33 @@
1
+ module Paperclip
2
+ # This module is intended as a compatability shim for the differences in
3
+ # callbacks between Rails 2.0 and Rails 2.1.
4
+ module CallbackCompatability
5
+ def self.included(base)
6
+ base.extend(ClassMethods)
7
+ base.send(:include, InstanceMethods)
8
+ end
9
+
10
+ module ClassMethods
11
+ # The implementation of this method is taken from the Rails 1.2.6 source,
12
+ # from rails/activerecord/lib/active_record/callbacks.rb, line 192.
13
+ def define_callbacks(*args)
14
+ args.each do |method|
15
+ self.class_eval <<-"end_eval"
16
+ def self.#{method}(*callbacks, &block)
17
+ callbacks << block if block_given?
18
+ write_inheritable_array(#{method.to_sym.inspect}, callbacks)
19
+ end
20
+ end_eval
21
+ end
22
+ end
23
+ end
24
+
25
+ module InstanceMethods
26
+ # The callbacks in < 2.1 don't worry about the extra options or the
27
+ # block, so just run what we have available.
28
+ def run_callbacks(meth, opts = nil, &blk)
29
+ callback(meth)
30
+ end
31
+ end
32
+ end
33
+ end
@@ -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}"[0]])
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 #:nodoc:
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
@@ -0,0 +1,49 @@
1
+ module Paperclip
2
+ module Shoulda
3
+ module Matchers
4
+ def have_attached_file name
5
+ HaveAttachedFileMatcher.new(name)
6
+ end
7
+
8
+ class HaveAttachedFileMatcher
9
+ def initialize attachment_name
10
+ @attachment_name = attachment_name
11
+ end
12
+
13
+ def matches? subject
14
+ @subject = subject
15
+ responds? && has_column? && included?
16
+ end
17
+
18
+ def failure_message
19
+ "Should have an attachment named #{@attachment_name}"
20
+ end
21
+
22
+ def negative_failure_message
23
+ "Should not have an attachment named #{@attachment_name}"
24
+ end
25
+
26
+ def description
27
+ "have an attachment named #{@attachment_name}"
28
+ end
29
+
30
+ protected
31
+
32
+ def responds?
33
+ methods = @subject.instance_methods
34
+ methods.include?("#{@attachment_name}") &&
35
+ methods.include?("#{@attachment_name}=") &&
36
+ methods.include?("#{@attachment_name}?")
37
+ end
38
+
39
+ def has_column?
40
+ @subject.column_names.include?("#{@attachment_name}_file_name")
41
+ end
42
+
43
+ def included?
44
+ @subject.ancestors.include?(Paperclip::InstanceMethods)
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end