aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2017-07-28 15:13:22 -0500
committerDavid Heinemeier Hansson <david@loudthinking.com>2017-07-28 15:13:22 -0500
commit696b8c6f43214ed4b9b79f36a9f68de0db19f1ee (patch)
treef32ff450c846c23c54fb70f127a64a6da3cdf6f1
parentfd438769cc90882809de4ee469a1a999e8c026e6 (diff)
downloadrails-696b8c6f43214ed4b9b79f36a9f68de0db19f1ee.tar.gz
rails-696b8c6f43214ed4b9b79f36a9f68de0db19f1ee.tar.bz2
rails-696b8c6f43214ed4b9b79f36a9f68de0db19f1ee.zip
Add a direct_upload: true option to file_field_tag and Form#file_field
Then users don't have to bother with manually referring to internal routes.
-rw-r--r--README.md2
-rw-r--r--app/helpers/active_storage/file_field_with_direct_upload_helper.rb18
2 files changed, 19 insertions, 1 deletions
diff --git a/README.md b/README.md
index b127f87c5c..4a5f03233d 100644
--- a/README.md
+++ b/README.md
@@ -116,7 +116,7 @@ Active Storage, with its included JavaScript library, supports uploading directl
2. Annotate file inputs with the direct upload URL.
```ruby
- <%= form.file_field :attachments, multiple: true, data: { direct_upload_url: rails_direct_uploads_url } %>
+ <%= form.file_field :attachments, multiple: true, direct_upload: true %>
```
3. That's it! Uploads begin upon form submission.
diff --git a/app/helpers/active_storage/file_field_with_direct_upload_helper.rb b/app/helpers/active_storage/file_field_with_direct_upload_helper.rb
new file mode 100644
index 0000000000..87af79cdfd
--- /dev/null
+++ b/app/helpers/active_storage/file_field_with_direct_upload_helper.rb
@@ -0,0 +1,18 @@
+module ActiveStorage
+ # Temporary hack to overwrite the default file_field_tag and Form#file_field to accept a direct_upload: true option
+ # that then gets replaced with a data-direct-upload-url attribute with the route prefilled.
+ module FileFieldWithDirectUploadHelper
+ def file_field_tag(name, options = {})
+ text_field_tag(name, nil, convert_direct_upload_option_to_url(options.merge(type: :file)))
+ end
+
+ def file_field(object_name, method, options = {})
+ ActionView::Helpers::Tags::FileField.new(object_name, method, self, convert_direct_upload_option_to_url(options)).render
+ end
+
+ private
+ def convert_direct_upload_option_to_url(options)
+ options.merge('data-direct-upload-url': rails_direct_uploads_url) if options.delete(:direct_upload)
+ end
+ end
+end