在运行时更改ActiveStorage DirectDisk服务配置

问题描述 投票:0回答:1

我正在使用Rails 5.2和ActiveStorage 5.2.3和DirectDiskService

为了使用户上传的文件在目录中很好地分组,并且为了能够按我的意愿使用CDN(例如CloudFlare或CloudFront或其他任何文件,我试图在ApplicationController中设置一个方法来设置(本地)上传路径,例如:

class ApplicationController < ActionController::Base
  before_action :set_uploads_path

  # ...

private
  def set_upload_paths
     # this doesn't work
     ActiveStorage::Service::DirectDiskService.set_root p: "users/#{current_user.username}"
     # ... expecting the new root to become "public/users/yaddayadda"
  end
end

在config / initializers / active_storage.rb中,我有:

module SetDirectDiskServiceRoot
    def set_root(p:)
        @root = Rails.root.join("public", p)
        @public_root = p
        @public_root.prepend('/') unless @public_root.starts_with?('/')
    end
end

ActiveStorage::Service::DirectDiskService.module_eval { attr_writer :root }
ActiveStorage::Service::DirectDiskService.class_eval { include SetDirectDiskServiceRoot }

它的确让我在服务的新实例上设置了根目录,但在Rails应用程序正在使用的实例上却没有。

我做错了什么?或如何完成此任务?

我正在使用Rails 5.2和ActiveStorage 5.2.3和DirectDiskService。为了使用户上载在目录中很好地分组,并能够按我的喜好使用CDN(例如CloudFlare或...

ruby-on-rails rails-activestorage
1个回答
0
投票

这是一个肮脏的骇客,它可以帮助您将本地(磁盘)上传保持在public / websites / domain_name / uploads

© www.soinside.com 2019 - 2024. All rights reserved.