Last active
January 2, 2019 19:00
-
-
Save monorkin/f56c5155801630b778ccb0d3425b850d to your computer and use it in GitHub Desktop.
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
# This code is license under the MIT license | |
# Full text: https://opensource.org/licenses/MIT | |
# Author Stanko K.R. <[email protected]> | |
# Usage: | |
# ```ruby | |
# user.avatar = S3UrlToShrineObjectConverter.call( | |
# arguments[:input][:avatar][:url], | |
# name: arguments[:input][:avatar][:filename] | |
# ) | |
require 'uri' | |
class S3UrlToShrineObjectConverter | |
def self.call(*args) | |
new(*args).call | |
end | |
def initialize(url, name: nil) | |
@url = url | |
@name = name | |
end | |
def call | |
return unless object&.exists? | |
{ | |
id: id, | |
storage: storage, | |
metadata: { | |
size: object.content_length, | |
filename: name || id, | |
mime_type: object.content_type | |
} | |
} | |
end | |
protected | |
attr_reader :url | |
attr_reader :name | |
private | |
def object | |
@object ||= bucket.object(uri.path) | |
end | |
def uri | |
@uri ||= URI(url) | |
end | |
def bucket | |
@bucket ||= begin | |
s3 = AWS::S3.new({}) # TODO: configure this | |
s3.buckets['your_bucket_name'] # TODO: load this from the app's config | |
end | |
end | |
def id | |
@id ||= uri.path.split('/', 2).last | |
end | |
def storage | |
@storage ||= uri.path.split('/', 2).first | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment