module Polypaperclip::ClassMethods

Public Instance Methods

has_attachment(name, options = {}) click to toggle source
# File lib/polypaperclip.rb, line 15
def has_attachment(name, options = {})
  initialize_polypaperclip
  
  polypaperclip_definitions[name] = {:validations => []}.merge(options)
  
  has_one "#{name}_attachment",
    :as => :attachable,
    :dependent => :destroy,
    :class_name => "Polypaperclip::PersistedAttachment",
    :conditions => "attachment_type = '#{name}'"
  
  define_method name do |*args|
    a = paperclip_attachment_for(name)
    (args.length > 0) ? a.to_s(args.first) : a
  end

  define_method "#{name}=" do |file|
    paperclip_attachment_for(name).assign(file)
  end

  define_method "#{name}?" do
    paperclip_attachment_for(name).file?
  end
  
  validates_each(name) do |record, attr, value|
    attachment = record.paperclip_attachment_for(name)
    attachment.send(:flush_errors)
  end
end
polypaperclip_definitions() click to toggle source
# File lib/polypaperclip.rb, line 11
def polypaperclip_definitions
  read_inheritable_attribute(:polypaperclip_definitions)
end

Protected Instance Methods

has_many_attachments_association() click to toggle source
# File lib/polypaperclip.rb, line 62
def has_many_attachments_association
  unless self.respond_to?(:attachments)
    has_many :attachments,
      :class_name => "Polypaperclip::PersistedAttachment",
      :as => :attachable
  end
end
initialize_polypaperclip() click to toggle source

initialize a polypaperclip model if a configuration hasn’t already been loaded

# File lib/polypaperclip.rb, line 47
def initialize_polypaperclip
  if polypaperclip_definitions.nil?
    after_save :save_attached_files
    before_destroy :destroy_attached_files
    
    has_many_attachments_association
  
    write_inheritable_attribute(:polypaperclip_definitions, {})
    
    #sequence is important here - we have to override some paperclip stuff
    include Paperclip::InstanceMethods
    include InstanceMethods
  end
end