shrine
shrine copied to clipboard
Tempfile plugins causes Shrine::Error file must be opened
Brief Description
I have a simple file attachment uploader that stores files in GCS storage. On my model before_save callback I store the size of the image file in my database by accessing:
class Comment
before_save :store_file_size
include CommentUploader::Attachment(:file)
def store_file_size
file.size
end
end
Expected behavior
The tempfile plugin should not affect normal behavior that works fine when the tempfile plugin is not used.
Actual behavior
When I add the tempfile plugin, I get a Shrine::Error - uploaded file must be opened. Calling file.open prior to file.size or file.dimensions works. The tempfile plugin is forcing a requirement to call file.open
System configuration
Ruby version: 2.5.0
Shrine version: 3.3.0
Thanks for an amazing gem and for your consideration of this issue.
saving size in a column
If all you want to do is to save the size of the file in a separate column, may I suggest using the metadata attributes plugin?
class CommentUploader < Shrine
plugin :metadata_attributes, :size => :size
end
# just make sure you have an appropriate size column available e.g. comment_size or whatever it is.
automatic opening of the tempfile
it is an interesting suggestion. i would be interested to know what the others think about the pros/cons of this approach.
the functionality pointed out this looks like the intended behaviour of the library.
I suspect the mainainers would prefer the discussion to take place here: https://discourse.shrinerb.com/t/tempfile-plugins-causes-shrine-error-file-must-be-opened/475
best rgds
@vanboom When Shrine internally opens an uploaded file, it switches #size
to read from that file, so that metadata extraction could get the actual filesize.
When the uploaded file is closed, the reference to the internal file remains, and attempts to read it will fail. I'm not sure yet how the tempfile plugin manifests this behaviour in your case, I will take a look.
We could consider removing the intenrnal reference to the IO object when an uploaded file is closed. I don't remember now why I originally wanted the reference to stay, maybe so it can act as other IO objects. But I don't see a gain at the moment.
@benkoshy GitHub issues are fine for this one, this could be considered a bug.