Class: Shimmer::FileProxy

Inherits:
Object
  • Object
show all
Defined in:
lib/shimmer/utils/file_proxy.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(blob_id:, width: nil, height: nil) ⇒ FileProxy

Returns a new instance of FileProxy.



36
37
38
39
# File 'lib/shimmer/utils/file_proxy.rb', line 36

def initialize(blob_id:, width: nil, height: nil)
  @blob_id = blob_id
  @resize = [width&.to_i, height&.to_i] if width || height
end

Instance Attribute Details

#blob_idObject (readonly)

Returns the value of attribute blob_id.



5
6
7
# File 'lib/shimmer/utils/file_proxy.rb', line 5

def blob_id
  @blob_id
end

Class Method Details

.message_verifierObject



31
32
33
# File 'lib/shimmer/utils/file_proxy.rb', line 31

def message_verifier
  @message_verifier ||= ApplicationRecord.signed_id_verifier
end

.parse_resize(resize) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/shimmer/utils/file_proxy.rb', line 18

def parse_resize(resize)
  return if resize.blank?
  return resize if resize.is_a?(Array)

  # In the past, we generated the IDs with ImageMagick style "200x200>" strings. We don't do that anymore, but to prevent all old URLs breaking and caches invalidating at once, we grandfather these URLs in.
  matches = resize.match(/(?<width>\d*)x(?<height>\d*)/)

  [
    matches[:width].presence&.to_i,
    matches[:height].presence&.to_i
  ]
end

.restore(id) ⇒ Object



11
12
13
14
15
16
# File 'lib/shimmer/utils/file_proxy.rb', line 11

def restore(id)
  blob_id, resize = message_verifier.verified(id)
  width, height = parse_resize(resize)

  new(blob_id: blob_id, width: width, height: height)
end

Instance Method Details

#blobObject



49
50
51
# File 'lib/shimmer/utils/file_proxy.rb', line 49

def blob
  @blob ||= ActiveStorage::Blob.find(blob_id)
end

#fileObject



62
63
64
# File 'lib/shimmer/utils/file_proxy.rb', line 62

def file
  @file ||= blob.service.download(variant.key)
end

#pathObject



41
42
43
# File 'lib/shimmer/utils/file_proxy.rb', line 41

def path
  Rails.application.routes.url_helpers.file_path(id, locale: nil)
end

#url(protocol: Rails.env.production? ? :https : :http) ⇒ Object



45
46
47
# File 'lib/shimmer/utils/file_proxy.rb', line 45

def url(protocol: Rails.env.production? ? :https : :http)
  Rails.application.routes.url_helpers.file_url(id, locale: nil, protocol: protocol)
end

#variantObject



53
54
55
56
57
58
59
60
# File 'lib/shimmer/utils/file_proxy.rb', line 53

def variant
  @variant ||= if blob.representable?
    options = {resize_to_limit: @resize, format: "webp"}
    blob.representation(options.compact).processed
  else
    blob
  end
end