How to set filename when reading from StringIO

1,896 views
Skip to first unread message

camad...@gmail.com

unread,
Jun 8, 2017, 6:26:26 AM6/8/17
to Shrine
Hi,

I'm using StringIO to read an image file stored in a database, resulting in nil original_filename:

class UserImage < ApplicationRecord
  include
UserImageUploader[:image]
end

# On rails console:
> u = UserImage.new
> u.image = StringIO.new(other_model.image)
> u.image.metadata
{
     
"filename" => nil,
         
"size" => 24426,
   
"mime_type" => "image/jpeg"
}
> u.image.metadata['filename'] = 'myfile.png'
"myfile.png"
> u.image.metadata['filename']
nil

How can I asign a filename to the uploaded file?

Besides, is there a better way of doing that?

Many thanks.

Janko Marohnić

unread,
Jun 9, 2017, 12:40:04 AM6/9/17
to camad...@gmail.com, Shrine
On assignment Shrine writes cached file data to the `#image_data` column in JSON format. When you retrieve the cached file, Shrine parses the JSON data into a Hash, and instantiates a Shrine::UploadedFile object from it. What you did is modify the Shrine::UploadedFile object, but the updated data won't automatically get written to the `#image_data` column. A Shrine::UploadedFile object doesn't know about model attributes, it only has the data Hash it was instantiated with. So when you modify the Shrine::UploadedFile object, and call the attachment reader method, it will return a new Shrine::UploadedFile object instantiated from JSON string returned by `#image_data`, which hasn't changed.

You need to write the updated Shrine::UploadedFile object back to the #image_data column attribute:

u = UserImage.new

u.image = StringIO.new(other_model.image)

cached_file = u.image

cached_file.metadata["filename"] = "myfile.png"

u.image_data = cached_file.to_json


Kind regards,
Janko

--
You received this message because you are subscribed to the Google Groups "Shrine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-shrine+unsubscribe@googlegroups.com.
To post to this group, send email to ruby-...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ruby-shrine/f4cf8769-ae0e-4bbe-a82a-69bef30ecc2b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

camad...@gmail.com

unread,
Jun 9, 2017, 3:59:29 AM6/9/17
to Shrine, camad...@gmail.com
Oh, now I see. I completly misunderstood the thing.

I'm sorry for such a noob question.

Thank you.
Reply all
Reply to author
Forward
0 new messages