Posted 12 days ago. Visible to the public. Linked content. Auto-destruct in 48 days
Updated: Writing strings as Carrierwave uploads
We do need a custom class after all 😳
- When you have string contents (e.g. a generated binary stream, or data from a remote source) that you want to store as a file using Carrierwave, here is a simple solution.
- While you could write your string to a file and pass that file to Carrierwave, why even bother? You already have your string (or stream).
- However, a plain StringIO object will not work for Carrierwave's ActiveRecord integration:
->> Attachment.create!(file: StringIO.new(string)) -# TypeError: no implicit conversion of nil into String
-This is because Carrierwave expects the file upload to respond to `#original_filename`. -To do so you can use [`Rack::Test::UploadedFile`](https://www.rubydoc.info/github/brynary/rack-test/Rack/Test/UploadedFile), which adds an `#original_filename` method to any `IO` object:
-stream = StringIO.new(string) -file = Rack::Test::UploadedFile.new(stream, original_filename: 'document.pdf')
-While that class sounds like it would not be available in production environments, it actually is.