Methods
Public Instance methods
attachment_background_for(name, background)

When processing, if the spawn plugin is installed, processing can be done in a background fork or thread if desired.

     # File lib/data_base/attachment.rb, line 247
247:         def attachment_background_for(name, background)
248:           attachment_definitions[name][:background] = background
249:         end
attachment_convert_options_for(name, convert_name, convert_options)

When creating thumbnails, use this free-form options field to pass in various convert command options. Typical options are "-strip" to remove all Exif data from the image (save space for thumbnails and avatars) or "-depth 8" to specify the bit depth of the resulting conversion. See ImageMagick convert documentation for more options: (www.imagemagick.org/script/convert.php) Note that this option takes a hash of options, each of which correspond to the style of thumbnail being generated. You can also specify :all as a key, which will apply to all of the thumbnails being generated. If you specify options for the :original, it would be best if you did not specify destructive options, as the intent of keeping the original around is to regenerate all the thumbnails when requirements change.

  attachment_styles          :avatar, :large,    "300x300"
  attachment_styles          :avatar, :negative, "100x100"
  attachment_convert_options :avatar, :all,      "-strip"
  attachment_convert_options :avatar, :negative, "-negate"
     # File lib/data_base/attachment.rb, line 240
240:         def attachment_convert_options_for(name, convert_name, convert_options)
241:           attachment_definitions[name][:convert_options] ||= {}
242:           attachment_definitions[name][:convert_options].merge!(convert_name => convert_options)
243:         end
attachment_default_style_for(name, default_style)

The thumbnail style that will be used by default URLs. Defaults to original.

  attachment_styles :avatar, :normal, "100x100#"
  attachment_default_style :normal
  user.avatar.url # => "/avatars/23/normal_me.png"
     # File lib/data_base/attachment.rb, line 207
207:         def attachment_default_style_for(name, default_style)
208:           attachment_definitions[name][:default_style] = default_style
209:         end
attachment_default_url_for(name, url)

The URL that will be returned if there is no attachment assigned. This field is interpolated just as the url is. The default value is

  "/images/backend/no-image.png"
  has_one_attached_file :avatar
  attachment_default_url :avatar, "/images/backend/no-image.png"
  User.new.avatar.url(:small) # => "/images/backend/no-image.png"
     # File lib/data_base/attachment.rb, line 179
179:         def attachment_default_url_for(name, url)
180:           attachment_definitions[name][:default_url] = url
181:         end
attachment_definitions()

Returns the attachment definitions defined by each call to has_attached_file.

     # File lib/data_base/attachment.rb, line 366
366:         def attachment_definitions
367:           read_inheritable_attribute(:attachment_definitions)
368:         end
attachment_path_for(name, path)

The path were the attachment are stored. The default value is

  :rails_root/public/uploads/:id_:attachment_:style_:basename.:extension

This value must be in consistency with url

     # File lib/data_base/attachment.rb, line 187
187:         def attachment_path_for(name, path)
188:           attachment_definitions[name][:path] = path
189:         end
attachment_processors_for(name, processor_name, processors)

Attachment supports an extendible selection of post-processors. When you define a set of styles for an attachment, by default it is expected that those "styles" are actually "thumbnails". However, you can do more than just thumbnail images. By defining a subclass of Lipsiadmin::Attachment::Processor, you can perform any processing you want on the files that are attached. Any file in your Rails app‘s lib/attachment_processors directory is automatically loaded by Attachment, allowing you to easily define custom processors. You can specify a processor with the :processors option to has_attached_file:

  attachment_styles     :avatar, :text, { :quality => :better }
  attachment_processors :avatar, :ocr

This would load the hypothetical class Lipsiadmin::Ocr, which would have the hash "{ :quality => :better }" passed to it along with the uploaded file. For more information about defining processors, see Lipsiadmin::Attachment::Processor.

The default processor is Lipsiadmin::Attachment::Thumbnail. For backwards compatability reasons, you can pass a single geometry string or an array containing a geometry and a format, which the file will be converted to, like so:

  attachment_styles     :avatar, :thumb, ["32x32#", :png]

This will convert the "thumb" style to a 32x32 square in png format, regardless of what was uploaded. If the format is not specified, it is kept the same (i.e. jpgs will remain jpgs).

Multiple processors can be specified, and they will be invoked in the order they are defined in the :processors array. Each successive processor will be given the result of the previous processor‘s execution. All processors will receive the same parameters, which are what you define in the :styles hash. For example, assuming we had this definition:

  attachment_styles     :avatar, :text, { :quality => :better }
  attachment_processors :avatar, :rotator
  attachment_processors :avatar, :ocr

then both the :rotator processor and the :ocr processor would receive the options "{ :quality => :better }". This parameter may not mean anything to one or more or the processors, and they are free to ignore it.

     # File lib/data_base/attachment.rb, line 290
290:         def attachment_processors_for(name, processor_name, processors)
291:           attachment_definitions[name][:processors] ||= {}
292:           attachment_definitions[name][:processors].merge!(processor_name => processor_processors)
293:         end
attachment_storage_for(name, storage)

Chooses the storage backend where the files will be stored. The current choices are :filesystem and :s3. The default is :filesystem. Make sure you read the documentation for Lipsiadmin::Attachment::Storage::Filesystem and Lipsiadmin::Attachment::Storage::S3 for backend-specific options.

     # File lib/data_base/attachment.rb, line 222
222:         def attachment_storage_for(name, storage)
223:           attachment_definitions[name][:storage] = storage
224:         end
attachment_styles_for(name, style_name, styles)

A hash of thumbnail styles and their geometries. You can find more about geometry strings at the ImageMagick website (www.imagemagick.org/script/command-line-options.php#resize). Attachment also adds the "#" option (e.g. "50x50#"), which will resize the image to fit maximally inside the dimensions and then crop the rest off (weighted at the center). The default value is to generate no thumbnails.

     # File lib/data_base/attachment.rb, line 197
197:         def attachment_styles_for(name, style_name, styles)
198:           attachment_definitions[name][:styles] ||= {}
199:           attachment_definitions[name][:styles].merge!(style_name => styles)
200:         end
attachment_url_for(name, url)

The full URL of where the attachment is publically accessible. This can just as easily point to a directory served directly through Apache as it can to an action that can control permissions. You can specify the full domain and path, but usually just an absolute path is sufficient. The leading slash must be included manually for absolute paths. The default value is

  "/uploads/:id_:attachment_:style_:basename.:extension". See
  Lipsiadmin::Attachment::Attach#interpolate for more information on variable interpolaton.
  :url => "/:class/:attachment/:id/:style_:basename.:extension"
  :url => "http://some.other.host/stuff/:class/:id_:extension"
     # File lib/data_base/attachment.rb, line 169
169:         def attachment_url_for(name, url)
170:           attachment_definitions[name][:url] = url
171:         end
attachment_whiny_for(name, whiny_thumbnails)

Will raise an error if Attachment cannot post_process an uploaded file due to a command line error. This will override the global setting for this attachment. Defaults to false.

     # File lib/data_base/attachment.rb, line 214
214:         def attachment_whiny_for(name, whiny_thumbnails)
215:           attachment_definitions[name][:whiny_thumbnails] = whiny_thumbnails
216:         end
has_many_attachments(name, options = {})

Attach a many files/images to your model.

  Examples:

    has_one_attachment                    :images
    attachment_styles_for                 :images, :normal, "128x128!"
    validates_attachment_presence_for     :images
    validates_attachment_size_for         :images, :greater_than => 10.megabytes
    validates_attachment_content_type_for :images, "image/png"

Then in your form (with multipart) you can simply add:

  -fields_for "yourmodel[images_attributes][]", @yourmodel.images.build do |image|
    =image.file_field :file
     # File lib/data_base/attachment.rb, line 111
111:         def has_many_attachments(name, options = {})
112:           options[:as]         ||= :attacher
113:           options[:class_name] ||= "Attachment"
114:           
115:           # We need to check if the attachment model allow multiple attachments
116:           multi_attachments = options[:class_name].constantize.column_names.include?("attacher_name")
117:           
118:           options[:conditions]   = "attacher_name = '#{name}'" if multi_attachments
119: 
120:           has_many name, options
121:           before_save "before_save_for_#{name}"
122:           attr_accessor "#{name}_attributes"
123: 
124:           write_inheritable_attribute(:attachment_definitions, {}) if attachment_definitions.nil?
125:           attachment_definitions[name] = {:validations => {}}.merge(reflections[name].class_name.constantize.attachment_definitions)
126: 
127:           validates_each(name) do |record, attr, value|
128:             attributes = record.send("#{name}_attributes")
129:             attributes ||= {}
130: 
131:             file_column = nil
132:             for attribute in attributes
133:               attribute.merge!(:attachment_definitions => record.class.attachment_definitions[name])
134:               file_column = reflections[name].class_name.constantize.new(attribute)
135:               unless file_column.valid?
136:                 file_column.errors.each do |error, message|
137:                   record.errors.add(name, message) if message
138:                 end
139:               end
140:             end
141:           end
142: 
143:           define_method "before_save_for_#{name}" do
144:             attributes = send("#{name}_attributes")
145:             attributes ||= {}
146: 
147:             file_column = nil
148: 
149:             for attribute in attributes
150:               next if attribute["file"].blank?
151:               attribute.merge!(:attachment_definitions => self.class.attachment_definitions[name])
152:               # We need to add the new attacher_name
153:               attribute.merge!(:attacher_name => name.to_s) if multi_attachments
154:               self.send(name).build(attribute)
155:             end
156: 
157:           end
158:         end
has_one_attachment(name, options={})

Attach a single file/image to your model.

  Examples:

    has_one_attachment                    :image
    attachment_styles_for                 :image, :normal, "128x128!"
    validates_attachment_presence_for     :image
    validates_attachment_size_for         :image, :greater_than => 10.megabytes
    validates_attachment_content_type_for :image, "image/png"

Then in your form (with multipart) you can simply add:

  =file_field_tag "yourmodel[image_attributes][file]"

or

  -fields_for "yourmodel[image_attributes][file]", @yourmodel.build_image do |image|
    =image.file_field :file
    # File lib/data_base/attachment.rb, line 47
47:         def has_one_attachment(name, options={})
48:           options[:as]         ||= :attacher
49:           options[:class_name] ||= "Attachment"
50:           
51:           # We need to check if the attachment model allow multiple attachments
52:           multi_attachments = options[:class_name].constantize.column_names.include?("attacher_name")
53:           
54:           options[:conditions]   = "attacher_name = '#{name}'" if multi_attachments
55:           
56:           has_one name, options
57:           before_save "before_save_for_#{name}"
58:           attr_accessor "#{name}_attributes"
59: 
60:           write_inheritable_attribute(:attachment_definitions, {}) if attachment_definitions.nil?
61:           attachment_definitions[name] = {:validations => {}}.merge(reflections[name].class_name.constantize.attachment_definitions)
62: 
63:           validates_each(name) do |record, attr, value|
64:             attributes = record.send("#{name}_attributes")
65:             attributes ||= {}
66: 
67:             attributes.merge!(:attachment_definitions => record.class.attachment_definitions[name])
68:             file_column = reflections[name].class_name.constantize.new(attributes)
69:             unless file_column.valid?
70:               file_column.errors.each do |error, message|
71:                 record.errors.add(name, message) if message
72:               end
73:             end
74:           end
75: 
76:           define_method "before_save_for_#{name}" do
77:             attributes = send("#{name}_attributes")
78:             attributes ||= {}
79:             
80:             return if attributes[:file].blank?
81:             
82:             attributes.merge!(:attachment_definitions => self.class.attachment_definitions[name])
83:             
84:             # We need to add the new attacher_name
85:             attributes.merge!(:attacher_name => name.to_s) if multi_attachments
86:             
87:             if file_column = self.send(name)
88:               file_column.update_attributes(attributes)
89:             else
90:               self.send("build_#{name}", attributes)
91:             end
92: 
93:           end
94:         end
validates_attachment_content_type_for(name, *args)

Places ActiveRecord-style validations on the content type of the file assigned. The possible options are:

  • content_type: Allowed content types. Can be a single content type or an array. Each type can be a String or a Regexp. It should be noted that Internet Explorer upload files with content_types that you may not expect. For example, JPEG images are given image/pjpeg and PNGs are image/x-png, so keep that in mind when determining how you match. Allows all by default.
  • message: The message to display when the uploaded file has an invalid content type.
     # File lib/data_base/attachment.rb, line 345
345:         def validates_attachment_content_type_for(name, *args)
346:           options = {}
347:           valid_types = []
348:           args.each do |variable|
349:             case variable
350:               when Hash   then options.merge!(variable)
351:               else valid_types << variable
352:             end
353:           end
354:           attachment_definitions[name][:validations][:content_type] = lambda do |attachment, instance|
355:             unless attachment.original_filename.blank?
356:               content_type = attachment.instance_read(:content_type)
357:               unless valid_types.any?{ |t| t === content_type }
358:                 options[:message] || I18n.t("activerecord.errors.messages.content_type")
359:               end
360:             end
361:           end
362:         end
validates_attachment_presence_for(name, options = {})

Places ActiveRecord-style validations on the presence of a file.

     # File lib/data_base/attachment.rb, line 328
328:         def validates_attachment_presence_for(name, options = {})
329:           message = options[:message] || I18n.t("activerecord.errors.messages.blank")
330:           attachment_definitions[name][:validations][:presence] = lambda do |attachment, instance|
331:             message unless attachment.exist?
332:           end
333:         end
validates_attachment_size_for(name, options = {})

Places ActiveRecord-style validations on the size of the file assigned. The possible options are:

  • in: a Range of bytes (i.e. +1..1.megabyte+),
  • less_than: equivalent to :in => 0..options[:less_than]
  • greater_than: equivalent to :in => options[:greater_than]..Infinity
  • message: error message to display, use :min and :max as replacements
     # File lib/data_base/attachment.rb, line 301
301:         def validates_attachment_size_for(name, options = {})
302:           min     = options[:greater_than] || (options[:in] && options[:in].first) || 0
303:           max     = options[:less_than]    || (options[:in] && options[:in].last)  || (1.0/0)
304:           range   = (min..max)
305:           helper  = ActionController::Base.helpers
306: 
307:           if options[:message].blank?
308:             message  = ""
309:             message << I18n.t("activerecord.errors.messages.greater_than", :count => helper.number_to_human_size(min))    if min > 0
310:             message << " " + I18n.t("activerecord.errors.messages.less_than", :count => helper.number_to_human_size(max)) if max.to_f.infinite? != 1
311:           else
312:             message = options[:message]
313:           end
314: 
315:           attachment_definitions[name][:validations][:size] = lambda do |attachment, instance|
316:             if attachment.exist? && !range.include?(attachment.size.to_i)
317:               message
318:             end
319:           end
320:         end
validates_attachment_thumbnails_for(name, options = {})

Adds errors if thumbnail creation fails. The same as specifying :whiny_thumbnails => true.

     # File lib/data_base/attachment.rb, line 323
323:         def validates_attachment_thumbnails_for(name, options = {})
324:           attachment_definitions[name][:whiny_thumbnails] = true
325:         end