Gregg
Gregg

Reputation: 51

Dynamic EC2 Bucket Options for Fog/Carrierwave

I have a Rails3 application which uses Carrierwave and Fog to store data to Amazon's S3. This application I am building requires that I allow each user to have their own secure EC2 bucket. The premise of the application is that the user will create a account (devise) and I will generate a storage bucket just for that user under my application's EC2 User and Password. Based on the current documentation, I have not seen a way to have multiple buckets as this is configured in the FOG YML. I would like to ask for alternatives to set this FOG_DIRECTORY dynamically based on the user attributes.

I know there is a way to manage dynamic folders, but this will not work as I need dedicated buckets by user.

Thanks in advance!

Upvotes: 5

Views: 968

Answers (1)

codingFoo
codingFoo

Reputation: 906

Assuming your buckets already exist. Try the following:

#config/initializers/carrierwave.rb

CarrierWave.configure do |config|
  #...other configuration stuff...
  config.fog_directory = 'null.example.com'

  config.fog_host = proc do
    proc do |file|
      uploader = file.instance_variable_get :@uploader
      "http://#{uploader.fog_directory}"
    end
  end
end

Note the nested procs, as of the writing of the this answer the documentation for carrierwave is incorrect. If you want the fog_host to be dynamic, you have to wrap the proc so that the carrierwave configuration class does the right thing.

Even though the fog_directory is set dynamically later. Test frameworks and such complain if something is not set in the initializer(it things work correctly the setting is always overridden).

#app/controllers/application_controller.rb

before_filter :set_bucket

def set_bucket
  CarrierWave.configure do |config|
    config.fog_directory = "#{current_user.id}.bucket.example.com"
  end
end

Change the set_bucket function to suit your bucket naming convention.

You can add some conditional logic if you want a fixed bucket in development rather than a bucket per user.

Also this blog post outlines another approach.

Upvotes: 3

Related Questions