Robert Klemme
7/12/2007 2:02:00 PM
2007/7/12, Ronald Fischer <ronald.fischer@venyon.com>:
> > > file=Tempfile.new('.tempreq','/thome/requests')
> > > file << '....' # populate the file
> > > path=file.path # remember the generated filename
> > > file.close
> > > result=path+'.xml' # add desired extension to the filename
> > > File.rename(path,result) # rename file
> > > at_exit { File::delete(result) } # remove file at exit
> > >
> > > When the exit handler jumps into action, I get however the following
> > > error:
> > >
> > > H:\thome\grubylib/TfwCommon.rb:433:in `delete': Permission denied -
> > > /thome/requests/.tempr
> > > eq.3176.0.xml (Errno::EACCES)
> > >
> > > After the program has ended, I can however erase the file from the
> > > command line with
> > > no problems. Why do I get a "permission denied" here? Is
> > there a better
> > > way to
> > > achieve my goal?
> >
> > I'd just use the block form:
> >
> > ruby -r tempfile -e 'Tempfile.open("foo", ".") {|io| io.puts 123}'
>
>
> Hmmm... I don't see how this solves my file rename problem.
Ah, my bad: I overread that one. File renaming is a bad idea with tempfiles.
> Don't forget
> that I need to rename the temporary file, so that it has the extension
> .xml, before I continue processing it. The logic basically should go
> like this (pseudocode):
>
> 1. create temporary file
> 2. fill temporary file and close it
> 3. rename it, so that it ends in .xml
> 4. pass its file name to some library function, which processes the
> file
> 5. when my application exits, delete that xml file
>
> Tempfile::open with block argument performs steps 1 and 2 above, but
> doesn't
> tell me the name of the temporary file:
>
> x=Tempfile.open("foo", ".") {|io| io.puts 123}
> x.class
> => NilClass
In that case rather use your own mechanism. That's too far away from
tempfile's functionality. For example
def tmp_xml(base, dir, mode)
file_name = File.join(dir, "#{base}-#{rand 1000}.xml")
begin
File.open(file_name, mode) do |io|
yield io, file_name
end
ensure
File.unlink file_name if File.exists? file_name
end
end
Then you can do
tmp_xml ".", "foo", "rw" do |io, name|
puts "file is #{name}"
...
end
Kind regards
robert