ruby-on-railsamazon-s3ruby-on-rails-5shrine

Can I add Shrine upload credentials to the model


I have a multi-tenant site built on rails 5, each of the tenants adds their own s3 credentials, therefore, any uploads that happen on their tenant site get uploaded to their own s3 account.

The problem I have at the moment is that Shrine seems to only let me add s3 credentials in the initializer. This works great but I would like to add it to the model so that I can dynamically populate the s3 credentials depending on which tenant is being used at the time. Does anyone know anyway shrine can help me?

I managed to do this with paperclip but it came with other problems such as background processing etc.


Solution

  • You could define all the storages in the initializer:

    Shrine.storages = {
      first_storage: Shrine::Storage::S3.new(
      bucket: "my-first-bucket", # required 
      region: "eu-west-1", # required 
      access_key_id: "abc",
      secret_access_key: "xyz"),
    
      second_storage: Shrine::Storage::S3.new(
      bucket: "my-second-bucket", # required 
      region: "eu-east-1", # required 
      access_key_id: "efg",
      secret_access_key: "uvw")
    }
    

    Note: This is not all the storages code - both the :cache and the :store storages should be defined.

    And then use them in the models:

    class Photo
      include ImageUploader::Attachment(:image)
    end
    
    photo = Photo.new
    photo.image_attacher.upload(io, :first_storage)
    photo.image_attacher.upload(other_io, :second_storage)
    

    See Shrine attacher's doc page and source code