Sha256: 11d3af550b4ad6d7a13cf33988a29735b074b8c83d58a633b833fb062c654d00

Contents?: true

Size: 1.3 KB

Versions: 6

Compression:

Stored size: 1.3 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
            )
        end

        virtual_attribute = "new_#{attribute}_uuids"
      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").last
        end

        virtual_attribute = "new_#{attribute}_uuid"
      end

      attr_accessor virtual_attribute

      association_method = "associate_#{attribute}"

      after_save association_method

      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

6 entries across 6 versions & 1 rubygems

Version Path
s3_relay-0.3.1 lib/s3_relay/model.rb
s3_relay-0.3.0 lib/s3_relay/model.rb
s3_relay-0.2.0 lib/s3_relay/model.rb
s3_relay-0.1.0 lib/s3_relay/model.rb
s3_relay-0.0.3 lib/s3_relay/model.rb
s3_relay-0.0.2 lib/s3_relay/model.rb