Created
July 12, 2023 03:12
-
-
Save zgid123/5b32db97ac2617dd2ac0b071646f61b9 to your computer and use it in GitHub Desktop.
Attach existing s3 url for ActiveStorage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # frozen_string_literal: true | |
| # This monkey-patching is for creating records using url | |
| # instead of reupload the file using attach of activestorage | |
| # this is useful for SPA | |
| module ActiveStorage | |
| module BlobParser | |
| def parse_blob(attachable) | |
| key, filename, content_type = parse_url(attachable) | |
| io = URI.parse(attachable).open | |
| ActiveStorage::Blob.build_after_unfurling( | |
| io: io, | |
| key: key, | |
| identify: true, | |
| filename: filename, | |
| content_type: content_type | |
| ) | |
| end | |
| def parse_blob_param(blob) | |
| { | |
| key: blob.key, | |
| filename: blob.filename, | |
| metadata: blob.metadata, | |
| checksum: blob.checksum, | |
| byte_size: blob.byte_size, | |
| content_type: blob.content_type, | |
| service_name: blob.service_name | |
| } | |
| end | |
| private | |
| def parse_url(url) | |
| *_, key, filename = url.split('/') | |
| key = "store/#{key}" if url.include?('store/') | |
| content_type = MIME::Types.type_for(filename).first.content_type | |
| [key, filename, content_type] | |
| end | |
| end | |
| class Attached | |
| class Many | |
| include ActiveStorage::BlobParser | |
| def attach_url(attachables, replace: false) | |
| attachables = [attachables] unless attachables.is_a?(Array) | |
| blobs = attachables.map do |attachable| | |
| parse_blob(attachable) | |
| end | |
| blob_collection = record.send(name).blobs | |
| blob_collection.each(&:purge) if replace | |
| blob_collection.create(blobs.map { |blob| parse_blob_param(blob) }) | |
| end | |
| end | |
| class One | |
| include ActiveStorage::BlobParser | |
| def attach_url(attachable) | |
| blob = parse_blob(attachable) | |
| blob.save | |
| ActiveStorage::Attachment.create( | |
| name: name, | |
| record: record, | |
| blob: blob | |
| ) | |
| end | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment