pandaman pandaman - 6 months ago 21
Ruby Question

How to get the name of an instance of Tempfile in Ruby?

When creating a Tempfile in ruby, it takes the

basename
you pass it, and then it appends a random string to the end.

From the docs: http://ruby-doc.org/stdlib-1.9.3/libdoc/tempfile/rdoc/Tempfile.html

file = Tempfile.new('hello')
file.path # => something like: "/tmp/hello2843-8392-92849382--0"


You can see it starts with
hello
and then adds
2843-8392-92849382--0
. Though this ending will change every time you create an instance.

This makes it difficult (at least for me) to lookup in the directory its saved in.

Question:

Is there any method (like
file.fullName
) that could be run on the instance to just get the
hello2843-8392-92849382--0
, in order to look it up in the directory where its saved?

Thoughts:

You could take the
path
and parse it but that seems excessive.

Answer

Basically you're asking for:

File.basename(file.path)

There's rarely a reason to need that exposed as a method, but if you want you could subclass Tempfile to add it in:

class SuperTempfile < Tempfile
  def basename
    File.basename(path)
  end
end