/
variant_with_record.rb
54 lines (43 loc) · 1.27 KB
/
variant_with_record.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 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.downcase}",
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