Home > Blockchain >  How to resolve url for static asset in S3 with DefaultUrl plugin
How to resolve url for static asset in S3 with DefaultUrl plugin

Time:06-30

i'm having trouble finding the correct way to generate a S3 URL for a public static asset through the default_url plugin in Shrine. The asset is the users avatar, which can be nil, so the idea was to use the plugin default_url to get the empty avatar image. Following the docs I've arrived to this:

class AvatarUploader < Shrine
  plugin :default_url

  Attacher.default_url do |options|
    '/user_avatar.png'
  end
end

But this generates a relative URL. I've also tried using the :host option as pointed out here. But it only works if I hardcode the complete endpoing URL, which is no good.

plugin :default_url, host: "https://my-public-bucket.s3.amazonaws.com"

attacher.url #=> "https://my-public-bucket.s3.amazonaws.com/user_avatar.png" 

Other option would be, to set the bucket name in an environment variable:

plugin :default_url, host: "https://#{ENV["S3BUCKET_PUBLIC"]}.s3.amazonaws.com"

but I think is not good either.

Is there a way to programmatically create the full URL directly from Shrine, using its existing configs?

CodePudding user response:

To programmatically create the URL I needed to call Shrine#uploaded_file with an options hash:

class AvatarUploader < Shrine
  plugin :default_url
  
  Attacher.default_url do |options|
    data = { "id" => "user_avatar.png", "storage" => :bucket_name_from_config }
    shrine_class.uploaded_file(data).url
  end
end
  • Related