Albert Callarisa Roca

Tech blog

Detecting File type in arguments

06 Feb 2013

The other day I needed a method that, based on a file sent in one of the arguments, uploads that file to S3 and returns its URL.

Initially I started with somehting like


def upload(file)
  if file.is_a?(IO)
    content = file.read
    # ...
  end
end
  

Since a File is a subclass of IO, that should work, but it didn't.

The problem was that the file is not directly a File, it's an uploaded file to Rails, and them seem to be a Tempfile. And it happens that Tempfile is not a File, so it's not an IO.

So I had to extend the code to detect also Tempfile.

Not very happy with that, still didn't work.

The problem now is that Rails file parameters are instances of a wrapper class with the file in one of the attributes. I didn't want to add another if for this new instance type, so I changed the code for


def upload(file)
  if file.responds_to?(:read)
    content = file.read
    # ...
  end
end
  

I don't really like this, but it is something all the classes have in common.

Does anyone encounter this issue before? Am I missing something here?