module AttachmentSaver::BaseMethods

Public Instance Methods

saves_attachment(options = {}) click to toggle source
# File lib/attachment_saver.rb, line 6
def saves_attachment(options = {})
  extend ClassMethods
  include InstanceMethods
  
  class_attribute :attachment_options
  self.attachment_options = options

  attachment_options[:datastore] ||= 'file_system'
  require "datastores/#{attachment_options[:datastore].to_s.underscore}"
  include DataStores.const_get(attachment_options[:datastore].to_s.classify)
  before_validation :before_validate_attachment # this callback does things like override the content-type based on the actual file data
  before_save       :save_attachment # this callback is where most of the goodness happens; note that it runs before save, so that it prevents the record being saved if processing raises; this is why our filenames can't be based on the instance ID
  after_save        :tidy_attachment
  after_save        :close_open_file
  after_destroy     :delete_attachment

  if attachment_options[:formats] && reflect_on_association(:formats).nil? # this allows you to override our definition of the sizes association by simply defining it before calling has_attachment
    attachment_options[:processor] ||= 'image_science'
    attachment_options[:derived_class] ||= DerivedImage
    has_many :formats, :as => :original, :class_name => attachment_options[:derived_class].to_s, :dependent => :destroy
    after_save      :save_updated_derived_children
  end
  
  if attachment_options[:processor]
    unless Object.const_defined?(:Processors) && Processors.const_defined?(attachment_options[:processor].to_s.classify)
      require "processors/#{attachment_options[:processor].to_s.underscore}"
    end
    include Processors.const_get(attachment_options[:processor].to_s.classify)
  end
end