Feature #504

Tempfile.open should return the new tempfile rather than nil

Added by Tyler Rick over 6 years ago. Updated about 4 years ago.

[ruby-core:18394]
Status:Closed
Priority:Normal
Assignee:Yukihiro Matsumoto

Description

=begin
It seems like you ought to be able to do this
f = Tempfile.open("foo") do |f|
f.print("foo\n")
end
p f.path

but curretnly Tempfile.open returns nil.

I propose the following patch:

--- /usr/lib/ruby/1.9.0/tempfile.old.rb 2008-08-27 01:50:02.000000000 -0700
+++ /usr/lib/ruby/1.9.0/tempfile.rb 2008-08-27 01:51:03.000000000 -0700
@@ -182,15 +182,15 @@
tempfile = new(*args)

    if block_given?
  • begin
  • yield(tempfile)
  • ensure
  • tempfile.close
  • end
  • begin
  • yield(tempfile)
  • ensure
  • tempfile.close
  •    end
    
  • nil

  •    tempfile
    else
    
  • tempfile

  •    tempfile
    end
    

    end
    end
    @@ -204,5 +204,12 @@
    f.open
    p f.gets # => "foo\n"
    f.close!
    -end

  • f = Tempfile.open("foo") do |f|

  • f.print("foo\n")

  • end

  • p f.path # => "/tmp/foo20080827-5200-7awus9-0"

  • f.open

  • p f.gets # => "foo\n"

  • f.close!
    +end
    =end

History

#1 Updated by Tyler Rick over 6 years ago

=begin
Currently, if you want to be able to do anything with the tempfile after the block ends, you have to do something like this, which isn't very elegant:

file = nil
Tempfile.open("foo") do |f|
file = nil
f.print("foo\n")
end
p file.path

=end

#2 Updated by Gregory Brown over 6 years ago

=begin
As far as I can tell, this is not a bug, as it is documented.

However, I would support a behavior change here. I can't think of very many uses of the block form in the current case, unless you want to do ugly workarounds.

It would be quite nice if it returned a closed filehandle.
=end

#3 Updated by Koichi Sasada over 6 years ago

  • Assignee set to Yukihiro Matsumoto

=begin

=end

#4 Updated by Yukihiro Matsumoto over 6 years ago

  • Status changed from Open to Closed
  • % Done changed from 0 to 100

=begin
Applied in changeset r19454.
=end

Also available in: Atom PDF