Monkey patch Active Storage to set content type when uploading to S3
authorTom Hughes <tom@compton.nu>
Fri, 5 Jul 2019 13:31:04 +0000 (14:31 +0100)
committerTom Hughes <tom@compton.nu>
Tue, 9 Jul 2019 18:17:56 +0000 (19:17 +0100)
config/initializers/active_storage.rb [new file with mode: 0644]

diff --git a/config/initializers/active_storage.rb b/config/initializers/active_storage.rb
new file mode 100644 (file)
index 0000000..3d2c912
--- /dev/null
@@ -0,0 +1,31 @@
+Rails.configuration.after_initialize do
+  require "active_storage/service/s3_service"
+  require_dependency "active_storage/variant"
+
+  module OpenStreetMap
+    module ActiveStorage
+      module Variant
+        private
+
+        def upload(image)
+          File.open(image.path, "r") { |file| service.upload(key, file, :content_type => content_type) }
+        end
+      end
+
+      module S3Service
+        def upload(key, io, content_type:, **options)
+          @upload_options[:content_type] = content_type
+          super(key, io, **options)
+          @upload_options.delete(:content_type)
+        end
+      end
+    end
+  end
+
+  ActiveStorage::Variant.prepend(OpenStreetMap::ActiveStorage::Variant)
+  ActiveStorage::Service::S3Service.prepend(OpenStreetMap::ActiveStorage::S3Service)
+
+  ActiveSupport::Reloader.to_complete do
+    ActiveStorage::Variant.prepend(OpenStreetMap::ActiveStorage::Variant)
+  end
+end