Daniel Vandersluis
Daniel Vandersluis

Reputation: 94143

Kernel#open with a passed in File object

I'm trying to debug/diagnose some strange behaviour, and hoping someone can have some insight for me. This is in Ruby 1.9.3.

We've got some code that opens an uploaded file to determine its MIME type, which boils down to:

open(file) { |f| get_mime_type(f) }

Pretty straightforward. In this case, file is actually a File object (or a Rack::Test::UploadedFile in our test suite), not a path, but open seems to work fine with a file object.

... Except that we now have a new member of the team and it's not working for him. His environment is set up for the most part the same way (anything relevant I could think of is identical - ruby version and patchlevel, rails version, installed gems), but on his machine, when a file object is passed to open, it returns a file object and ignores the block altogether. Passing in a path instead of a file object, however, works:

open(file.path) { |f| get_mime_type(f) }

So that's our temporary fix, but what I'm trying to figure out is why this is happening? I'd appreciate any insight!

Upvotes: 3

Views: 289

Answers (1)

Shoe
Shoe

Reputation: 76240

What I'm trying to figure out is why this is happening?

The first argument of Kernel#open is not supposed to work with a File object but rather with a String object representing a path. The fact that it is working for some machines is not the proof of it being valid or a suggested way of using open.

You should definitely keep using:

open(file.path) { |f| get_mime_type(f) }

Upvotes: 1

Related Questions