[Feature] [ActiveStorage] ActiveStorage custom storage path configuration per Model attribute

319 views
Skip to first unread message

Frantisek Rokusek

unread,
Jan 7, 2020, 7:33:13 AM1/7/20
to Ruby on Rails: Core
Hello Rails Team!
First of all I want to thank you for all job that you make here!!! Rails is a wonderful framework to work with.

I am creating an issue because I am not sure I have understood all functionalities of ActiveStorage. My pull request is not quite ready...

Here is my issue: **ActiveStorage custom storage path configuration per Model attribute**

Here is our business issue: *We use the [apartment gem](https://github.com/influitive/apartment) to split our datas on a client basis and we want to make the same with uploaded files and store them in separate folders.*

**thoughtbot** has made a wonderfull [paperclip gem](https://github.com/thoughtbot/paperclip), but since it is deprecated we are in the process of switching to ActiveStorage all our attachments management.

In Paperclip there is a fine feature where you can choose a [specific storage path](https://github.com/thoughtbot/paperclip) for each of the model attachable attribute and interpolate values in it as follows:

```ruby
# app/models/user.rb

# in Paperclip
has_attached_file :avatar,
                  path: ':tenant/users/:user_id/:hash/:filename'
```

### Expected behaviour
Being able to configure a custom path.
The idea is to make this possible in ActiveStorage too and have something like that:

```ruby
# app/models/user.rb

# in future ActiveStorage
has_one_attached :avatar,
                 path: ':tenant/users/:id/:unique_secure_token'
```

### Our current solution
For the moment we have made a *monkey_patching* to implement those storage path by changing the `ActiveStorage::Blob#key`.

```ruby
# app/models/user.rb

def document=(attachable)
  document.attach(create_blob(attachable))
end

def attachable_storage_path
  [
    Apartment::Tenant.current.parameterize,
    'users',
    id,
    ActiveStorage::Blob.generate_unique_secure_token
  ].compact.join('/')
end
```


```ruby
# app/models/application_record.rb

def attachable_storage_path
  raise NotImplementedError
end

def create_blob(attachable)
  return if attachable.nil?

  ActiveStorage::Blob.new.tap do |blob|
    blob.filename = attachable.original_filename
    blob.key = attachable_storage_path
    blob.upload(attachable)
    blob.save!
  end
end
```

### Future solution
I have began to make a PR on ActiveStorage but want to have your feedback on this feature before digging deeper in this problematic and validate the right direction!

Here it is: https://github.com/frantisekrokusekpa/rails/pull/1/files

Thank you for your feedback and advices!

Reply all
Reply to author
Forward
0 new messages