Sha256: 68ae20672d1c2232b77f7a7829280c0e5ba4ccc85c6dc1a66f6cad63336cbc7c

Contents?: true

Size: 1.26 KB

Versions: 9

Compression:

Stored size: 1.26 KB

Contents

# frozen_string_literal: true

class ActiveStorage::VariantWithRecord
  attr_reader :blob, :variation

  def initialize(blob, variation)
    @blob, @variation = blob, ActiveStorage::Variation.wrap(variation)
  end

  def processed
    process
    self
  end

  def process
    transform_blob { |image| create_or_find_record(image: image) } unless processed?
  end

  def processed?
    record.present?
  end

  def image
    record&.image
  end

  delegate :key, :url, :download, to: :image, allow_nil: true

  alias_method :service_url, :url
  deprecate service_url: :url

  private
    def transform_blob
      blob.open do |input|
        variation.transform(input) do |output|
          yield io: output, filename: "#{blob.filename.base}.#{variation.format}",
            content_type: variation.content_type, service_name: blob.service.name
        end
      end
    end

    def create_or_find_record(image:)
      @record =
        ActiveRecord::Base.connected_to(role: ActiveRecord::Base.writing_role) do
          blob.variant_records.create_or_find_by!(variation_digest: variation.digest) do |record|
            record.image.attach(image)
          end
        end
    end

    def record
      @record ||= blob.variant_records.find_by(variation_digest: variation.digest)
    end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
activestorage-6.1.3.2 app/models/active_storage/variant_with_record.rb
activestorage-6.1.3.1 app/models/active_storage/variant_with_record.rb
activestorage-6.1.3 app/models/active_storage/variant_with_record.rb
activestorage-6.1.2.1 app/models/active_storage/variant_with_record.rb
activestorage-6.1.2 app/models/active_storage/variant_with_record.rb
activestorage-6.1.1 app/models/active_storage/variant_with_record.rb
activestorage-6.1.0 app/models/active_storage/variant_with_record.rb
activestorage-6.1.0.rc2 app/models/active_storage/variant_with_record.rb
activestorage-6.1.0.rc1 app/models/active_storage/variant_with_record.rb