PageRenderTime 45ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/plugins/paperclip/lib/paperclip.rb

https://github.com/dmitryame/railscollab
Ruby | 277 lines | 136 code | 33 blank | 108 comment | 8 complexity | ff56c9d21a704ada128e3ca513a9b491 MD5 | raw file
Possible License(s): AGPL-3.0, MIT
  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. require 'tempfile'
  28. require 'paperclip/upfile'
  29. require 'paperclip/iostream'
  30. require 'paperclip/geometry'
  31. require 'paperclip/thumbnail'
  32. require 'paperclip/storage'
  33. require 'paperclip/attachment'
  34. # The base module that gets included in ActiveRecord::Base. See the
  35. # documentation for Paperclip::ClassMethods for more useful information.
  36. module Paperclip
  37. VERSION = "2.1.2"
  38. class << self
  39. # Provides configurability to Paperclip. There are a number of options available, such as:
  40. # * whiny_thumbnails: Will raise an error if Paperclip cannot process thumbnails of
  41. # an uploaded image. Defaults to true.
  42. # * image_magick_path: Defines the path at which to find the +convert+ and +identify+
  43. # programs if they are not visible to Rails the system's search path. Defaults to
  44. # nil, which uses the first executable found in the search path.
  45. def options
  46. @options ||= {
  47. :whiny_thumbnails => true,
  48. :image_magick_path => nil
  49. }
  50. end
  51. def path_for_command command #:nodoc:
  52. path = [options[:image_magick_path], command].compact
  53. File.join(*path)
  54. end
  55. def run cmd, params = "", expected_outcodes = 0
  56. output = `#{%Q[#{path_for_command(cmd)} #{params} 2>#{bit_bucket}].gsub(/\s+/, " ")}`
  57. unless [expected_outcodes].flatten.include?($?.exitstatus)
  58. raise PaperclipCommandLineError, "Error while running #{cmd}"
  59. end
  60. output
  61. end
  62. def bit_bucket
  63. File.exists?("/dev/null") ? "/dev/null" : "NUL"
  64. end
  65. def included base #:nodoc:
  66. base.extend ClassMethods
  67. end
  68. end
  69. class PaperclipError < StandardError #:nodoc:
  70. end
  71. class PaperclipCommandLineError < StandardError #:nodoc:
  72. end
  73. class NotIdentifiedByImageMagickError < PaperclipError #:nodoc:
  74. end
  75. module ClassMethods
  76. # +has_attached_file+ gives the class it is called on an attribute that maps to a file. This
  77. # is typically a file stored somewhere on the filesystem and has been uploaded by a user.
  78. # The attribute returns a Paperclip::Attachment object which handles the management of
  79. # that file. The intent is to make the attachment as much like a normal attribute. The
  80. # thumbnails will be created when the new file is assigned, but they will *not* be saved
  81. # until +save+ is called on the record. Likewise, if the attribute is set to +nil+ is
  82. # called on it, the attachment will *not* be deleted until +save+ is called. See the
  83. # Paperclip::Attachment documentation for more specifics. There are a number of options
  84. # you can set to change the behavior of a Paperclip attachment:
  85. # * +url+: The full URL of where the attachment is publically accessible. This can just
  86. # as easily point to a directory served directly through Apache as it can to an action
  87. # that can control permissions. You can specify the full domain and path, but usually
  88. # just an absolute path is sufficient. The leading slash must be included manually for
  89. # absolute paths. The default value is
  90. # "/:class/:attachment/:id/:style_:basename.:extension". See
  91. # Paperclip::Attachment#interpolate for more information on variable interpolaton.
  92. # :url => "/:attachment/:id/:style_:basename:extension"
  93. # :url => "http://some.other.host/stuff/:class/:id_:extension"
  94. # * +default_url+: The URL that will be returned if there is no attachment assigned.
  95. # This field is interpolated just as the url is. The default value is
  96. # "/:class/:attachment/missing_:style.png"
  97. # has_attached_file :avatar, :default_url => "/images/default_:style_avatar.png"
  98. # User.new.avatar_url(:small) # => "/images/default_small_avatar.png"
  99. # * +styles+: A hash of thumbnail styles and their geometries. You can find more about
  100. # geometry strings at the ImageMagick website
  101. # (http://www.imagemagick.org/script/command-line-options.php#resize). Paperclip
  102. # also adds the "#" option (e.g. "50x50#"), which will resize the image to fit maximally
  103. # inside the dimensions and then crop the rest off (weighted at the center). The
  104. # default value is to generate no thumbnails.
  105. # * +default_style+: The thumbnail style that will be used by default URLs.
  106. # Defaults to +original+.
  107. # has_attached_file :avatar, :styles => { :normal => "100x100#" },
  108. # :default_style => :normal
  109. # user.avatar.url # => "/avatars/23/normal_me.png"
  110. # * +whiny_thumbnails+: Will raise an error if Paperclip cannot process thumbnails of an
  111. # uploaded image. This will ovrride the global setting for this attachment.
  112. # Defaults to true.
  113. # * +convert_options+: When creating thumbnails, use this free-form options
  114. # field to pass in various convert command options. Typical options are "-strip" to
  115. # remove all Exif data from the image (save space for thumbnails and avatars) or
  116. # "-depth 8" to specify the bit depth of the resulting conversion. See ImageMagick
  117. # convert documentation for more options: (http://www.imagemagick.org/script/convert.php)
  118. # Note that this option takes a hash of options, each of which correspond to the style
  119. # of thumbnail being generated. You can also specify :all as a key, which will apply
  120. # to all of the thumbnails being generated. If you specify options for the :original,
  121. # it would be best if you did not specify destructive options, as the intent of keeping
  122. # the original around is to regenerate all the thumbnails when requirements change.
  123. # has_attached_file :avatar, :styles => { :large => "300x300", :negative => "100x100" }
  124. # :convert_options => {
  125. # :all => "-strip",
  126. # :negative => "-negate"
  127. # }
  128. # * +storage+: Chooses the storage backend where the files will be stored. The current
  129. # choices are :filesystem and :s3. The default is :filesystem. Make sure you read the
  130. # documentation for Paperclip::Storage::Filesystem and Paperclip::Storage::S3
  131. # for backend-specific options.
  132. def has_attached_file name, options = {}
  133. include InstanceMethods
  134. write_inheritable_attribute(:attachment_definitions, {}) if attachment_definitions.nil?
  135. attachment_definitions[name] = {:validations => []}.merge(options)
  136. after_save :save_attached_files
  137. before_destroy :destroy_attached_files
  138. define_method name do |*args|
  139. a = attachment_for(name)
  140. (args.length > 0) ? a.to_s(args.first) : a
  141. end
  142. define_method "#{name}=" do |file|
  143. attachment_for(name).assign(file)
  144. end
  145. define_method "#{name}?" do
  146. attachment_for(name).file?
  147. end
  148. validates_each(name) do |record, attr, value|
  149. value.send(:flush_errors) unless value.valid?
  150. end
  151. end
  152. # Places ActiveRecord-style validations on the size of the file assigned. The
  153. # possible options are:
  154. # * +in+: a Range of bytes (i.e. +1..1.megabyte+),
  155. # * +less_than+: equivalent to :in => 0..options[:less_than]
  156. # * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
  157. # * +message+: error message to display, use :min and :max as replacements
  158. def validates_attachment_size name, options = {}
  159. attachment_definitions[name][:validations] << lambda do |attachment, instance|
  160. unless options[:greater_than].nil?
  161. options[:in] = (options[:greater_than]..(1/0)) # 1/0 => Infinity
  162. end
  163. unless options[:less_than].nil?
  164. options[:in] = (0..options[:less_than])
  165. end
  166. if attachment.file? && !options[:in].include?(attachment.instance_read(:file_size).to_i)
  167. min = options[:in].first
  168. max = options[:in].last
  169. if options[:message]
  170. options[:message].gsub(/:min/, min.to_s).gsub(/:max/, max.to_s)
  171. else
  172. "file size is not between #{min} and #{max} bytes."
  173. end
  174. end
  175. end
  176. end
  177. # Adds errors if thumbnail creation fails. The same as specifying :whiny_thumbnails => true.
  178. def validates_attachment_thumbnails name, options = {}
  179. attachment_definitions[name][:whiny_thumbnails] = true
  180. end
  181. # Places ActiveRecord-style validations on the presence of a file.
  182. def validates_attachment_presence name, options = {}
  183. attachment_definitions[name][:validations] << lambda do |attachment, instance|
  184. unless attachment.file?
  185. options[:message] || "must be set."
  186. end
  187. end
  188. end
  189. # Places ActiveRecord-style validations on the content type of the file assigned. The
  190. # possible options are:
  191. # * +content_type+: Allowed content types. Can be a single content type or an array.
  192. # Each type can be a String or a Regexp. It should be noted that Internet Explorer uploads
  193. # files with content_types that you may not expect. For example, JPEG images are given
  194. # image/pjpeg and PNGs are image/x-png, so keep that in mind when determining how you match.
  195. # Allows all by default.
  196. # * +message+: The message to display when the uploaded file has an invalid content type.
  197. def validates_attachment_content_type name, options = {}
  198. attachment_definitions[name][:validations] << lambda do |attachment, instance|
  199. valid_types = [options[:content_type]].flatten
  200. unless attachment.original_filename.blank?
  201. unless options[:content_type].blank?
  202. content_type = attachment.instance_read(:content_type)
  203. unless valid_types.any?{|t| t === content_type }
  204. options[:message] || "is not one of the allowed file types."
  205. end
  206. end
  207. end
  208. end
  209. end
  210. # Returns the attachment definitions defined by each call to has_attached_file.
  211. def attachment_definitions
  212. read_inheritable_attribute(:attachment_definitions)
  213. end
  214. end
  215. module InstanceMethods #:nodoc:
  216. def attachment_for name
  217. @attachments ||= {}
  218. @attachments[name] ||= Attachment.new(name, self, self.class.attachment_definitions[name])
  219. end
  220. def each_attachment
  221. self.class.attachment_definitions.each do |name, definition|
  222. yield(name, attachment_for(name))
  223. end
  224. end
  225. def save_attached_files
  226. logger.info("[paperclip] Saving attachments.")
  227. each_attachment do |name, attachment|
  228. attachment.send(:save)
  229. end
  230. end
  231. def destroy_attached_files
  232. logger.info("[paperclip] Deleting attachments.")
  233. each_attachment do |name, attachment|
  234. attachment.send(:queue_existing_for_delete)
  235. attachment.send(:flush_deletes)
  236. end
  237. end
  238. end
  239. end
  240. # Set it all up.
  241. if Object.const_defined?("ActiveRecord")
  242. ActiveRecord::Base.send(:include, Paperclip)
  243. File.send(:include, Paperclip::Upfile)
  244. end