Module: S3Relay::Model

Defined in:
lib/s3_relay/model.rb

Instance Method Summary collapse

Instance Method Details

#s3_relay(attribute, has_many = false) ⇒ Object



4
5
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
# File 'lib/s3_relay/model.rb', line 4

def s3_relay(attribute, has_many=false)

  upload_type = attribute.to_s.classify

  if has_many
    has_many attribute, as: :parent, class_name: "S3Relay::Upload"

    define_method attribute do
      S3Relay::Upload
        .where(
          parent_type: self.class.to_s,
          parent_id:   self.id,
          upload_type: upload_type
        ).to_a
    end
  else
    has_one attribute, as: :parent, class_name: "S3Relay::Upload"

    define_method attribute do
      S3Relay::Upload
        .where(
          parent_type: self.class.to_s,
          parent_id:   self.id,
          upload_type: upload_type
        )
        .order(:pending_at => 'desc').first
    end
  end

  virtual_attribute = "new_#{attribute}_uuids"
  attr_accessor virtual_attribute

  association_method = "associate_#{attribute}"

  after_save association_method.to_sym

  define_method association_method do
    new_uuids = send(virtual_attribute)
    return if new_uuids.blank?

    S3Relay::Upload.where(uuid: new_uuids, upload_type: upload_type)
      .update_all(parent_type: self.class.to_s, parent_id: self.id)
  end

end