Sha256: d4919eabd65b880b7cca553b0bbad1f865a360bd5d8186a696612e36b991342c

Contents?: true

Size: 1.26 KB

Versions: 5

Compression:

Stored size: 1.26 KB

Contents

module S3Relay
  module Model

    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

  end

end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
mongoid-direct-s3-upload-0.1.7 lib/s3_relay/model.rb
mongoid-direct-s3-upload-0.1.6 lib/s3_relay/model.rb
mongoid-direct-s3-upload-0.1.5 lib/s3_relay/model.rb
mongoid-direct-s3-upload-0.1.4 lib/s3_relay/model.rb
mongoid-direct-s3-upload-0.1.3 lib/s3_relay/model.rb