Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby tempfile anomalous behavior

This is my pry session output:

[1] pry(SomeTask)> epub
=> #<File:/somepath/tmp/x.epub>
[2] pry(SomeTask)> epub.size
=> 134
[3] pry(SomeTask)> File.size("/somepath/tmp/x.epub")
=> 44299
[4] pry(SomeTask)> epub.class
=> Tempfile

I see that File.size yields a different result than the size method of the Tempfile instance.

How is this possible?

like image 466
hrishikeshp19 Avatar asked Dec 30 '25 23:12

hrishikeshp19


1 Answers

The devil is in the details. From the docs for Tempfile#size (emphasis mine):

size()

Returns the size of the temporary file. As a side effect, the IO buffer is flushed before determining the size.

What's happening is that you're using File.size to read the size of the file before the buffer has been flushed—i.e. before all of the bytes have been written to the file—and then you're using Tempfile#size, which flushes that buffer before it calculates the size:

tmp = Tempfile.new('foo')
tmp.write('a' * 1000)
File.size(tmp)
# => 0
tmp.size
# => 1000

But see what happens when you call tmp.size before File.size(tmp):

tmp = Tempfile.new('bar')
tmp.write('a' * 1000)
tmp.size
# => 1000
File.size(tmp)
# => 1000

You can get the behavior you want out of File.size by manually flushing the buffer:

tmp = Tempfile.new('baz')
tmp.write('a' * 1000)
tmp.flush
File.size(tmp)
# => 1000
like image 68
Jordan Running Avatar answered Jan 02 '26 12:01

Jordan Running



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!