dm-paperclip-r3 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,47 @@
1
+ module Paperclip
2
+ # The Upfile module is a convenience module for adding uploaded-file-type methods
3
+ # to the +File+ class. Useful for testing.
4
+ # user.avatar = File.new("test/test_avatar.jpg")
5
+ module Upfile
6
+
7
+ # Infer the MIME-type of the file from the extension.
8
+ def content_type
9
+ type = (self.path.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase
10
+ case type
11
+ when %r"jpe?g" then "image/jpeg"
12
+ when %r"tiff?" then "image/tiff"
13
+ when %r"png", "gif", "bmp" then "image/#{type}"
14
+ when "txt" then "text/plain"
15
+ when %r"html?" then "text/html"
16
+ when "csv", "xml", "css", "js" then "text/#{type}"
17
+ else "application/x-#{type}"
18
+ end
19
+ end
20
+
21
+ # Returns the file's normal name.
22
+ def original_filename
23
+ File.basename(self.path)
24
+ end
25
+
26
+ # Returns the size of the file.
27
+ def size
28
+ File.size(self)
29
+ end
30
+ end
31
+ end
32
+
33
+ if defined? StringIO
34
+ class StringIO
35
+ attr_accessor :original_filename, :content_type
36
+ def original_filename
37
+ @original_filename ||= "stringio.txt"
38
+ end
39
+ def content_type
40
+ @content_type ||= "text/plain"
41
+ end
42
+ end
43
+ end
44
+
45
+ class File #:nodoc:
46
+ include Paperclip::Upfile
47
+ end
@@ -0,0 +1,124 @@
1
+ module Paperclip
2
+ module Validate
3
+
4
+ module ClassMethods
5
+
6
+ # Places ActiveRecord-style validations on the size of the file assigned. The
7
+ # possible options are:
8
+ # * +in+: a Range of bytes (i.e. +1..1.megabyte+),
9
+ # * +less_than+: equivalent to :in => 0..options[:less_than]
10
+ # * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
11
+ # * +message+: error message to display, use :min and :max as replacements
12
+ def validates_attachment_size(*fields)
13
+ opts = opts_from_validator_args(fields)
14
+ add_validator_to_context(opts, fields, Paperclip::Validate::SizeValidator)
15
+ end
16
+
17
+ # Adds errors if thumbnail creation fails. The same as specifying :whiny_thumbnails => true.
18
+ def validates_attachment_thumbnails name, options = {}
19
+ self.attachment_definitions[name][:whiny_thumbnails] = true
20
+ end
21
+
22
+ # Places ActiveRecord-style validations on the presence of a file.
23
+ def validates_attachment_presence(*fields)
24
+ opts = opts_from_validator_args(fields)
25
+ add_validator_to_context(opts, fields, Paperclip::Validate::RequiredFieldValidator)
26
+ end
27
+
28
+ # Places ActiveRecord-style validations on the content type of the file assigned. The
29
+ # possible options are:
30
+ # * +content_type+: Allowed content types. Can be a single content type or an array. Allows all by default.
31
+ # * +message+: The message to display when the uploaded file has an invalid content type.
32
+ def validates_attachment_content_type(*fields)
33
+ opts = opts_from_validator_args(fields)
34
+ add_validator_to_context(opts, fields, Paperclip::Validate::ContentTypeValidator)
35
+ end
36
+
37
+ end
38
+
39
+ class SizeValidator < DataMapper::Validate::GenericValidator #:nodoc:
40
+ def initialize(field_name, options={})
41
+ super
42
+ @field_name, @options = field_name, options
43
+ end
44
+
45
+ def call(target)
46
+ field_value = target.validation_property_value(:"#{@field_name}_file_size")
47
+ return true if field_value.nil?
48
+
49
+ @options[:in] = (@options[:greater_than]..(1/0)) unless @options[:greater_than].nil?
50
+ @options[:in] = (0..@options[:less_than]) unless @options[:less_than].nil?
51
+ return true if @options[:in].include? field_value.to_i
52
+
53
+ error_message ||= @options[:message] unless @options[:message].nil?
54
+ error_message ||= "%s must be less than %s bytes".t(Extlib::Inflection.humanize(@field_name), @options[:less_than]) unless @options[:less_than].nil?
55
+ error_message ||= "%s must be greater than %s bytes".t(Extlib::Inflection.humanize(@field_name), @options[:greater_than]) unless @options[:greater_than].nil?
56
+ error_message ||= "%s must be between %s and %s bytes".t(Extlib::Inflection.humanize(@field_name), @options[:in].first, @options[:in].last)
57
+ add_error(target, error_message , @field_name)
58
+ return false
59
+ end
60
+ end
61
+
62
+ class RequiredFieldValidator < DataMapper::Validate::GenericValidator #:nodoc:
63
+ def initialize(field_name, options={})
64
+ super
65
+ @field_name, @options = field_name, options
66
+ end
67
+
68
+ def call(target)
69
+ field_value = target.validation_property_value(@field_name)
70
+ if field_value.nil? || field_value.original_filename.blank?
71
+ error_message = @options[:message] || "%s must be set".t(Extlib::Inflection.humanize(@field_name))
72
+ add_error(target, error_message , @field_name)
73
+ return false
74
+ end
75
+ return true
76
+ end
77
+ end
78
+
79
+ class ContentTypeValidator < DataMapper::Validate::GenericValidator #:nodoc:
80
+ def initialize(field_name, options={})
81
+ super
82
+ @field_name, @options = field_name, options
83
+ end
84
+
85
+ def call(target)
86
+ valid_types = [@options[:content_type]].flatten
87
+ field_value = target.validation_property_value(@field_name)
88
+
89
+ unless field_value.nil? || field_value.original_filename.blank?
90
+ unless @options[:content_type].blank?
91
+ content_type = target.validation_property_value(:"#{@field_name}_content_type")
92
+ unless valid_types.any?{|t| t === content_type }
93
+ error_message ||= @options[:message] unless @options[:message].nil?
94
+ error_message ||= "%s's content type of '%s' is not a valid content type".t(Extlib::Inflection.humanize(@field_name), content_type)
95
+ add_error(target, error_message , @field_name)
96
+ return false
97
+ end
98
+ end
99
+ end
100
+
101
+ return true
102
+ end
103
+ end
104
+
105
+ class CopyAttachmentErrors < DataMapper::Validate::GenericValidator #:nodoc:
106
+ def initialize(field_name, options={})
107
+ super
108
+ @field_name, @options = field_name, options
109
+ end
110
+
111
+ def call(target)
112
+ field_value = target.validation_property_value(@field_name)
113
+ unless field_value.nil? || field_value.original_filename.blank?
114
+ return true if field_value.errors.length == 0
115
+ field_value.errors.each { |message| add_error(target, message, @field_name) }
116
+ return false
117
+ end
118
+ return true
119
+ end
120
+ end
121
+
122
+ end
123
+ end
124
+
@@ -0,0 +1,369 @@
1
+ # Paperclip allows file attachments that are stored in the filesystem. All graphical
2
+ # transformations are done using the Graphics/ImageMagick command line utilities and
3
+ # are stored in Tempfiles until the record is saved. Paperclip does not require a
4
+ # separate model for storing the attachment's information, instead adding a few simple
5
+ # columns to your table.
6
+ #
7
+ # Author:: Jon Yurek
8
+ # Copyright:: Copyright (c) 2008 thoughtbot, inc.
9
+ # License:: MIT License (http://www.opensource.org/licenses/mit-license.php)
10
+ #
11
+ # Paperclip defines an attachment as any file, though it makes special considerations
12
+ # for image files. You can declare that a model has an attached file with the
13
+ # +has_attached_file+ method:
14
+ #
15
+ # class User < ActiveRecord::Base
16
+ # has_attached_file :avatar, :styles => { :thumb => "100x100" }
17
+ # end
18
+ #
19
+ # user = User.new
20
+ # user.avatar = params[:user][:avatar]
21
+ # user.avatar.url
22
+ # # => "/users/avatars/4/original_me.jpg"
23
+ # user.avatar.url(:thumb)
24
+ # # => "/users/avatars/4/thumb_me.jpg"
25
+ #
26
+ # See the +has_attached_file+ documentation for more details.
27
+
28
+ require 'erb'
29
+ require 'tempfile'
30
+
31
+ require 'extlib'
32
+ require 'dm-core'
33
+
34
+ require 'dm-paperclip/upfile'
35
+ require 'dm-paperclip/iostream'
36
+ require 'dm-paperclip/geometry'
37
+ require 'dm-paperclip/processor'
38
+ require 'dm-paperclip/thumbnail'
39
+ require 'dm-paperclip/storage'
40
+ require 'dm-paperclip/interpolations'
41
+ require 'dm-paperclip/attachment'
42
+
43
+ # The base module that gets included in ActiveRecord::Base. See the
44
+ # documentation for Paperclip::ClassMethods for more useful information.
45
+ module Paperclip
46
+
47
+ VERSION = "2.4.1"
48
+
49
+ # To configure Paperclip, put this code in an initializer, Rake task, or wherever:
50
+ #
51
+ # Paperclip.configure do |config|
52
+ # config.root = Rails.root # the application root to anchor relative urls (defaults to Dir.pwd)
53
+ # config.env = Rails.env # server env support, defaults to ENV['RACK_ENV'] or 'development'
54
+ # config.use_dm_validations = true # validate attachment sizes and such, defaults to false
55
+ # config.processors_path = 'lib/pc' # relative path to look for processors, defaults to 'lib/paperclip_processors'
56
+ # end
57
+ #
58
+ def self.configure
59
+ yield @config = Configuration.new
60
+ Paperclip.config = @config
61
+ end
62
+
63
+ def self.config=(config)
64
+ @config = config
65
+ end
66
+
67
+ def self.config
68
+ @config ||= Configuration.new
69
+ end
70
+
71
+ def self.require_processors
72
+ return if @processors_already_required
73
+ Dir.glob(File.expand_path("#{Paperclip.config.processors_path}/*.rb")).sort.each do |processor|
74
+ require processor
75
+ end
76
+ @processors_already_required = true
77
+ end
78
+
79
+ class Configuration
80
+
81
+ DEFAULT_PROCESSORS_PATH = 'lib/paperclip_processors'
82
+
83
+ attr_writer :root, :env
84
+ attr_accessor :use_dm_validations
85
+
86
+ def root
87
+ @root ||= Dir.pwd
88
+ end
89
+
90
+ def env
91
+ @env ||= (ENV['RACK_ENV'] || 'development')
92
+ end
93
+
94
+ def processors_path=(path)
95
+ @processors_path = File.expand_path(path, root)
96
+ end
97
+
98
+ def processors_path
99
+ @processors_path ||= File.expand_path("../#{DEFAULT_PROCESSORS_PATH}", root)
100
+ end
101
+
102
+ end
103
+
104
+ class << self
105
+
106
+ # Provides configurability to Paperclip. There are a number of options available, such as:
107
+ # * whiny: Will raise an error if Paperclip cannot process thumbnails of
108
+ # an uploaded image. Defaults to true.
109
+ # * log: Logs progress to the Rails log. Uses ActiveRecord's logger, so honors
110
+ # log levels, etc. Defaults to true.
111
+ # * command_path: Defines the path at which to find the command line
112
+ # programs if they are not visible to Rails the system's search path. Defaults to
113
+ # nil, which uses the first executable found in the user's search path.
114
+ # * image_magick_path: Deprecated alias of command_path.
115
+ def options
116
+ @options ||= {
117
+ :whiny => true,
118
+ :image_magick_path => nil,
119
+ :command_path => nil,
120
+ :log => true,
121
+ :log_command => false,
122
+ :swallow_stderr => true
123
+ }
124
+ end
125
+
126
+ def path_for_command command #:nodoc:
127
+ if options[:image_magick_path]
128
+ warn("[DEPRECATION] :image_magick_path is deprecated and will be removed. Use :command_path instead")
129
+ end
130
+ path = [options[:command_path] || options[:image_magick_path], command].compact
131
+ File.join(*path)
132
+ end
133
+
134
+ def interpolates key, &block
135
+ Paperclip::Interpolations[key] = block
136
+ end
137
+
138
+ # The run method takes a command to execute and a string of parameters
139
+ # that get passed to it. The command is prefixed with the :command_path
140
+ # option from Paperclip.options. If you have many commands to run and
141
+ # they are in different paths, the suggested course of action is to
142
+ # symlink them so they are all in the same directory.
143
+ #
144
+ # If the command returns with a result code that is not one of the
145
+ # expected_outcodes, a PaperclipCommandLineError will be raised. Generally
146
+ # a code of 0 is expected, but a list of codes may be passed if necessary.
147
+ #
148
+ # This method can log the command being run when
149
+ # Paperclip.options[:log_command] is set to true (defaults to false). This
150
+ # will only log if logging in general is set to true as well.
151
+ def run cmd, params = "", expected_outcodes = 0
152
+ command = %Q<#{%Q[#{path_for_command(cmd)} #{params}].gsub(/\s+/, " ")}>
153
+ command = "#{command} 2>#{bit_bucket}" if Paperclip.options[:swallow_stderr]
154
+ Paperclip.log(command) if Paperclip.options[:log_command]
155
+ output = `#{command}`
156
+ unless [expected_outcodes].flatten.include?($?.exitstatus)
157
+ raise PaperclipCommandLineError, "Error while running #{cmd}"
158
+ end
159
+ output
160
+ end
161
+
162
+ def bit_bucket #:nodoc:
163
+ File.exists?("/dev/null") ? "/dev/null" : "NUL"
164
+ end
165
+
166
+ def included base #:nodoc:
167
+ base.extend ClassMethods
168
+ unless base.respond_to?(:define_callbacks)
169
+ base.send(:include, Paperclip::CallbackCompatability)
170
+ end
171
+ end
172
+
173
+ def processor name #:nodoc:
174
+ name = name.to_s.camel_case
175
+ processor = Paperclip.const_get(name)
176
+ unless processor.ancestors.include?(Paperclip::Processor)
177
+ raise PaperclipError.new("[paperclip] Processor #{name} was not found")
178
+ end
179
+ processor
180
+ end
181
+
182
+ # Log a paperclip-specific line. Uses ActiveRecord::Base.logger
183
+ # by default. Set Paperclip.options[:log] to false to turn off.
184
+ def log message
185
+ logger.info("[paperclip] #{message}") if logging?
186
+ end
187
+
188
+ def logger #:nodoc:
189
+ DataMapper.logger
190
+ end
191
+
192
+ def logging? #:nodoc:
193
+ options[:log]
194
+ end
195
+ end
196
+
197
+ class PaperclipError < StandardError #:nodoc:
198
+ end
199
+
200
+ class PaperclipCommandLineError < StandardError #:nodoc:
201
+ end
202
+
203
+ class NotIdentifiedByImageMagickError < PaperclipError #:nodoc:
204
+ end
205
+
206
+ class InfiniteInterpolationError < PaperclipError #:nodoc:
207
+ end
208
+
209
+ module Resource
210
+
211
+ def self.included(base)
212
+
213
+ base.class_eval <<-RUBY, __FILE__, __LINE__ + 1
214
+ class_variable_set(:@@attachment_definitions,nil) unless class_variable_defined?(:@@attachment_definitions)
215
+ def self.attachment_definitions
216
+ @@attachment_definitions
217
+ end
218
+
219
+ def self.attachment_definitions=(obj)
220
+ @@attachment_definitions = obj
221
+ end
222
+ RUBY
223
+
224
+ base.extend Paperclip::ClassMethods
225
+
226
+ # Done at this time to ensure that the user
227
+ # had a chance to configure the app in an initializer
228
+ if Paperclip.config.use_dm_validations
229
+ require 'dm-validations'
230
+ require 'dm-paperclip/validations'
231
+ base.extend Paperclip::Validate::ClassMethods
232
+ end
233
+
234
+ Paperclip.require_processors
235
+
236
+ end
237
+
238
+ end
239
+
240
+ module ClassMethods
241
+ # +has_attached_file+ gives the class it is called on an attribute that maps to a file. This
242
+ # is typically a file stored somewhere on the filesystem and has been uploaded by a user.
243
+ # The attribute returns a Paperclip::Attachment object which handles the management of
244
+ # that file. The intent is to make the attachment as much like a normal attribute. The
245
+ # thumbnails will be created when the new file is assigned, but they will *not* be saved
246
+ # until +save+ is called on the record. Likewise, if the attribute is set to +nil+ is
247
+ # called on it, the attachment will *not* be deleted until +save+ is called. See the
248
+ # Paperclip::Attachment documentation for more specifics. There are a number of options
249
+ # you can set to change the behavior of a Paperclip attachment:
250
+ # * +url+: The full URL of where the attachment is publically accessible. This can just
251
+ # as easily point to a directory served directly through Apache as it can to an action
252
+ # that can control permissions. You can specify the full domain and path, but usually
253
+ # just an absolute path is sufficient. The leading slash must be included manually for
254
+ # absolute paths. The default value is "/:class/:attachment/:id/:style_:filename". See
255
+ # Paperclip::Attachment#interpolate for more information on variable interpolaton.
256
+ # :url => "/:attachment/:id/:style_:basename:extension"
257
+ # :url => "http://some.other.host/stuff/:class/:id_:extension"
258
+ # * +default_url+: The URL that will be returned if there is no attachment assigned.
259
+ # This field is interpolated just as the url is. The default value is
260
+ # "/:class/:attachment/missing_:style.png"
261
+ # has_attached_file :avatar, :default_url => "/images/default_:style_avatar.png"
262
+ # User.new.avatar_url(:small) # => "/images/default_small_avatar.png"
263
+ # * +styles+: A hash of thumbnail styles and their geometries. You can find more about
264
+ # geometry strings at the ImageMagick website
265
+ # (http://www.imagemagick.org/script/command-line-options.php#resize). Paperclip
266
+ # also adds the "#" option (e.g. "50x50#"), which will resize the image to fit maximally
267
+ # inside the dimensions and then crop the rest off (weighted at the center). The
268
+ # default value is to generate no thumbnails.
269
+ # * +default_style+: The thumbnail style that will be used by default URLs.
270
+ # Defaults to +original+.
271
+ # has_attached_file :avatar, :styles => { :normal => "100x100#" },
272
+ # :default_style => :normal
273
+ # user.avatar.url # => "/avatars/23/normal_me.png"
274
+ # * +whiny_thumbnails+: Will raise an error if Paperclip cannot process thumbnails of an
275
+ # uploaded image. This will ovrride the global setting for this attachment.
276
+ # Defaults to true.
277
+ # * +convert_options+: When creating thumbnails, use this free-form options
278
+ # field to pass in various convert command options. Typical options are "-strip" to
279
+ # remove all Exif data from the image (save space for thumbnails and avatars) or
280
+ # "-depth 8" to specify the bit depth of the resulting conversion. See ImageMagick
281
+ # convert documentation for more options: (http://www.imagemagick.org/script/convert.php)
282
+ # Note that this option takes a hash of options, each of which correspond to the style
283
+ # of thumbnail being generated. You can also specify :all as a key, which will apply
284
+ # to all of the thumbnails being generated. If you specify options for the :original,
285
+ # it would be best if you did not specify destructive options, as the intent of keeping
286
+ # the original around is to regenerate all the thumbnails then requirements change.
287
+ # has_attached_file :avatar, :styles => { :large => "300x300", :negative => "100x100" }
288
+ # :convert_options => {
289
+ # :all => "-strip",
290
+ # :negative => "-negate"
291
+ # }
292
+ # * +storage+: Chooses the storage backend where the files will be stored. The current
293
+ # choices are :filesystem and :s3. The default is :filesystem. Make sure you read the
294
+ # documentation for Paperclip::Storage::Filesystem and Paperclip::Storage::S3
295
+ # for backend-specific options.
296
+ def has_attached_file name, options = {}
297
+ include InstanceMethods
298
+
299
+ self.attachment_definitions = {} if self.attachment_definitions.nil?
300
+ self.attachment_definitions[name] = {:validations => []}.merge(options)
301
+
302
+ property_options = options.delete_if { |k,v| ![ :public, :protected, :private, :accessor, :reader, :writer ].include?(key) }
303
+
304
+ property :"#{name}_file_name", String, property_options.merge(:length => 255)
305
+ property :"#{name}_content_type", String, property_options.merge(:length => 255)
306
+ property :"#{name}_file_size", Integer, property_options
307
+ property :"#{name}_updated_at", DateTime, property_options
308
+
309
+ after :save, :save_attached_files
310
+ before :destroy, :destroy_attached_files
311
+
312
+ # not needed with extlib just do before :post_process, or after :post_process
313
+ # define_callbacks :before_post_process, :after_post_process
314
+ # define_callbacks :"before_#{name}_post_process", :"after_#{name}_post_process"
315
+
316
+ define_method name do |*args|
317
+ a = attachment_for(name)
318
+ (args.length > 0) ? a.to_s(args.first) : a
319
+ end
320
+
321
+ define_method "#{name}=" do |file|
322
+ attachment_for(name).assign(file)
323
+ end
324
+
325
+ define_method "#{name}?" do
326
+ ! attachment_for(name).original_filename.blank?
327
+ end
328
+
329
+ if Paperclip.config.use_dm_validations
330
+ add_validator_to_context(opts_from_validator_args([name]), [name], Paperclip::Validate::CopyAttachmentErrors)
331
+ end
332
+
333
+ end
334
+
335
+ # Returns the attachment definitions defined by each call to
336
+ # has_attached_file.
337
+ def attachment_definitions
338
+ read_inheritable_attribute(:attachment_definitions)
339
+ end
340
+ end
341
+
342
+ module InstanceMethods #:nodoc:
343
+ def attachment_for name
344
+ @attachments ||= {}
345
+ @attachments[name] ||= Attachment.new(name, self, self.class.attachment_definitions[name])
346
+ end
347
+
348
+ def each_attachment
349
+ self.class.attachment_definitions.each do |name, definition|
350
+ yield(name, attachment_for(name))
351
+ end
352
+ end
353
+
354
+ def save_attached_files
355
+ Paperclip.log("Saving attachments.")
356
+ each_attachment do |name, attachment|
357
+ attachment.send(:save)
358
+ end
359
+ end
360
+
361
+ def destroy_attached_files
362
+ Paperclip.log("Deleting attachments.")
363
+ each_attachment do |name, attachment|
364
+ attachment.send(:queue_existing_for_delete)
365
+ attachment.send(:flush_deletes)
366
+ end
367
+ end
368
+ end
369
+ end
@@ -0,0 +1,38 @@
1
+ def obtain_class
2
+ class_name = ENV['CLASS'] || ENV['class']
3
+ raise "Must specify CLASS" unless class_name
4
+ @klass = Object.const_get(class_name)
5
+ end
6
+
7
+ def obtain_attachments
8
+ name = ENV['ATTACHMENT'] || ENV['attachment']
9
+ raise "Class #{@klass.name} has no attachments specified" unless @klass.respond_to?(:attachment_definitions)
10
+ if !name.blank? && @klass.attachment_definitions.keys.include?(name)
11
+ [ name ]
12
+ else
13
+ @klass.attachment_definitions.keys
14
+ end
15
+ end
16
+
17
+ namespace :paperclip do
18
+ desc "Regenerates thumbnails for a given CLASS (and optional ATTACHMENT)"
19
+ task :refresh => :environment do
20
+ klass = obtain_class
21
+ names = obtain_attachments
22
+ instances = klass.all
23
+
24
+ puts "Regenerating thumbnails for #{instances.length} instances of #{klass.name}:"
25
+ instances.each do |instance|
26
+ names.each do |name|
27
+ result = if instance.send("#{ name }?")
28
+ instance.send(name).reprocess!
29
+ instance.send(name).save
30
+ else
31
+ true
32
+ end
33
+ print result ? "." : "x"; $stdout.flush
34
+ end
35
+ end
36
+ puts " Done."
37
+ end
38
+ end