Module: Stratosphere::HasAttachment::ClassMethods

Defined in:
lib/stratosphere/has_attachment.rb

Instance Method Summary collapse

Instance Method Details

#has_attachment(name, options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/stratosphere/has_attachment.rb', line 6

def has_attachment(name, options={})
  cattr_accessor :attachment_name, :attachment_type
  
  self.attachment_name = name.to_sym
  self.attachment_type = options[:type]
  
  define_method "#{name}" do
    case options[:type]
      when :image
        Stratosphere::Image.new(self, name, options)
      when :video
        Stratosphere::Video.new(self, name, options)
      else
        Stratosphere::Attachment.new(self, name, options)
    end
  end

  send(:before_save) do
    if send(:"#{name}_file_changed?")
      attr = self[:"#{name}_file"]

      if [:image, :video].include? options[:type]
        if options[:type] == :image
          @attachment = Stratosphere::Image.new(self, name, options)
        elsif options[:type] == :video
          @attachment = Stratosphere::Video.new(self, name, options)
        end
      else
        @attachment = Stratosphere::Attachment.new(self, name, options)
      end

      if attr.nil? || attr.chomp == ''
        self[:"#{name}_file"]           = nil
        self[:"#{name}_content_type"]   = nil
        self[:"#{name}_content_length"] = nil
        @attachment.destroy!
      else
        @attachment.encode if @attachment.type == :video
      end
    end
  end

  self.send(:before_destroy) do
    case options[:type]
      when :image
        Stratosphere::Image.new(self, name, options).destroy!
      when :video
        Stratosphere::Video.new(self, name, options).destroy!
      else
        Stratosphere::Attachment.new(self, name, options).destroy!
    end
  end
end