|
1 | 1 | require 'active_storage/service/disk_service'
|
2 | 2 |
|
| 3 | +module FoodsoftActiveStorageDiskController |
| 4 | + def self.included(base) # :nodoc: |
| 5 | + base.class_eval do |
| 6 | + def show |
| 7 | + if key = decode_verified_key |
| 8 | + FoodsoftConfig.select_foodcoop(key[:scope]) |
| 9 | + serve_file named_disk_service(key[:service_name]).path_for(key[:key]), content_type: key[:content_type], disposition: key[:disposition] |
| 10 | + else |
| 11 | + head :not_found |
| 12 | + end |
| 13 | + rescue Errno::ENOENT |
| 14 | + head :not_found |
| 15 | + end |
| 16 | + end |
| 17 | + end |
| 18 | +end |
| 19 | + |
3 | 20 | module FoodsoftActiveStorageDiskService
|
4 | 21 | def self.included(base) # :nodoc:
|
5 | 22 | base.class_eval do
|
6 | 23 | def path_for(key)
|
7 | 24 | File.join root, FoodsoftConfig.scope, folder_for(key), key
|
8 | 25 | end
|
| 26 | + |
| 27 | + def generate_url(key, expires_in:, filename:, content_type:, disposition:) |
| 28 | + content_disposition = content_disposition_with(type: disposition, filename: filename) |
| 29 | + verified_key_with_expiration = ActiveStorage.verifier.generate( |
| 30 | + { |
| 31 | + key: key, |
| 32 | + scope: FoodsoftConfig.scope, |
| 33 | + disposition: content_disposition, |
| 34 | + content_type: content_type, |
| 35 | + service_name: name |
| 36 | + }, |
| 37 | + expires_in: expires_in, |
| 38 | + purpose: :blob_key |
| 39 | + ) |
| 40 | + |
| 41 | + if url_options.blank? |
| 42 | + raise ArgumentError, "Cannot generate URL for #{filename} using Disk service, please set ActiveStorage::Current.url_options." |
| 43 | + end |
| 44 | + |
| 45 | + url_helpers.rails_disk_service_url(verified_key_with_expiration, filename: filename, **url_options) |
| 46 | + end |
9 | 47 | end
|
10 | 48 | end
|
11 | 49 | end
|
12 | 50 |
|
13 | 51 | ActiveSupport.on_load(:after_initialize) do
|
14 | 52 | ActiveStorage::Service::DiskService.include FoodsoftActiveStorageDiskService
|
| 53 | + ActiveStorage::DiskController.include FoodsoftActiveStorageDiskController |
15 | 54 | end
|
0 commit comments