Module: SimpleFormAttachments::HasAttachments::ClassMethods

Defined in:
app/models/concerns/simple_form_attachments/has_attachments.rb

Instance Method Summary collapse

Instance Method Details

#attachment_accessor_namesObject



10
11
12
# File 'app/models/concerns/simple_form_attachments/has_attachments.rb', line 10

def attachment_accessor_names
  @@attachment_accessor_names ||= []
end

#has_many_attachments(accessor_name, opts = {}) ⇒ Object




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
# File 'app/models/concerns/simple_form_attachments/has_attachments.rb', line 16

def has_many_attachments accessor_name, opts={}
  attachment_accessor_names << accessor_name

  options = {
    class_name: opts[:class_name] || 'SimpleFormAttachments::Attachment',
    dependent: opts[:dependent],
    inverse_of: nil
  }

  has_and_belongs_to_many accessor_name, options do
    # FIXME: ideally the relation would return the attachments already sorted,
    # but that does not seem to be possible at the moment
    #
    # or at least we maintain the query and sort on the db level,
    # but as of not it is not possible to provide custom sort function to mongodb
    #
    define_method "sorted" do
      target.sort_by { |attachment| base.send("#{accessor_name.to_s.singularize}_ids").index(attachment.id) }
    end
  end

  accepts_nested_attributes_for accessor_name

  define_method "mark_#{accessor_name}_permanent" do
    self.send(accessor_name).update_all(temporary: false) if self.send(accessor_name)
  end
end

#has_one_attachment(accessor_name, opts = {}) ⇒ Object




46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'app/models/concerns/simple_form_attachments/has_attachments.rb', line 46

def has_one_attachment accessor_name, opts={}
  attachment_accessor_names << accessor_name

  options = {
    class_name: opts[:class_name] || 'SimpleFormAttachments::Attachment',
    dependent: opts[:dependent]
  }

  belongs_to accessor_name, options

  accepts_nested_attributes_for accessor_name

  define_method "mark_#{accessor_name}_permanent" do
    self.send(accessor_name).update(temporary: false) if self.send(accessor_name)
  end
end