Module: AttachmentMagic::ActMethods

Defined in:
lib/attachment_magic.rb

Instance Method Summary collapse

Instance Method Details

#has_attachment(options = {}) ⇒ Object

Options:

  • :content_type - Allowed content types. Allows all by default. Use :image to allow all standard image types.

  • :min_size - Minimum size allowed. 1 byte is the default.

  • :max_size - Maximum size allowed. 1.megabyte is the default.

  • :size - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.

  • :path_prefix - path to store the uploaded files. Uses public/#table_name by default.

  • :storage - Use :file_system to specify the attachment data is stored with the file system. Defaults to :file_system.

Examples:

has_attachment :max_size => 1.kilobyte
has_attachment :size => 1.megabyte..2.megabytes
has_attachment :content_type => 'application/pdf'
has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']


62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/attachment_magic.rb', line 62

def has_attachment(options = {})
  # this allows you to redefine the acts' options for each subclass, however
  options[:min_size]         ||= 1
  options[:max_size]         ||= 1.megabyte
  options[:size]             ||= (options[:min_size]..options[:max_size])
  options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? AttachmentMagic.content_types : t }.flatten unless options[:content_type].nil?

  extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods)
  include InstanceMethods unless included_modules.include?(InstanceMethods)

  parent_options = attachment_options || {}
  # doing these shenanigans so that #attachment_options is available to processors and backends
  self.attachment_options = options

  attachment_options[:storage]     ||= :file_system
  attachment_options[:storage]     ||= parent_options[:storage]
  attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
  if attachment_options[:path_prefix].nil?
    File.join("public", table_name)
  end
  attachment_options[:path_prefix]   = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/'

  unless File.directory?(AttachmentMagic.tempfile_path)
    FileUtils.mkdir_p(AttachmentMagic.tempfile_path)
  end

  storage_mod = AttachmentMagic::Backends.const_get("#{options[:storage].to_s.classify}Backend")
  include storage_mod unless included_modules.include?(storage_mod)

end