Module: BetterStorage::Attachment

Defined in:
lib/better_storage/attachment.rb

Instance Method Summary collapse

Instance Method Details

#public_url(style = :original) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/better_storage/attachment.rb', line 3

def public_url(style = :original)
  return nil unless persisted?

  key = if style == :original
    self.key
  else
    variants = record.attachment_reflections[name]&.variants
    transformations = variants.fetch(style) do
      record_model_name = record.to_model.model_name.name
      raise ArgumentError, "Cannot find variant :#{style} for #{record_model_name}##{name}"
    end
    transformation_key = ActiveStorage::Variation.wrap(transformations).digest
    variant_cache_key = "#{id}-#{transformation_key}"

    Rails.cache.fetch([:better_storage_public_url, variant_cache_key, BetterStorage::VERSION]) do
      variant(style).processed.key
    end
  end
  BetterStorage.public_url(key)
end