Module: Joint::ClassMethods

Defined in:
lib/joint/class_methods.rb

Instance Method Summary collapse

Instance Method Details

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



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
# File 'lib/joint/class_methods.rb', line 7

def attachment(name, options = {})
  options.symbolize_keys!
  name = name.to_sym

  self.attachment_names = attachment_names.dup.add(name)

  after_save     :save_attachments
  before_save    :nullify_nil_attachments_attributes
  after_save     :destroy_nil_attachments
  before_destroy :destroy_all_attachments

  key :"#{name}_id",   ObjectId
  key :"#{name}_name", String
  key :"#{name}_size", Integer
  key :"#{name}_type", String

  validates_presence_of(name) if options[:required]

  attachment_accessor_module.module_eval <<-EOC
    def #{name}
      @#{name} ||= AttachmentProxy.new(self, :#{name})
    end

    def #{name}?
      !nil_attachments.has_key?(:#{name}) && send(:#{name}_id?)
    end

    def #{name}=(file)
      if file.nil?
        nil_attachments[:#{name}] = send("#{name}_id")
        assigned_attachments.delete(:#{name})
      else
        send("#{name}_id=", BSON::ObjectId.new) if send("#{name}_id").nil?
        send("#{name}_name=", Joint.name(file))
        send("#{name}_size=", Joint.size(file))
        send("#{name}_type=", Joint.type(file))
        assigned_attachments[:#{name}] = file
        nil_attachments.delete(:#{name})
      end
    end
  EOC
end

#attachment_accessor_moduleObject



3
4
5
# File 'lib/joint/class_methods.rb', line 3

def attachment_accessor_module
  @attachment_accessor_module ||= Module.new
end