Skip to content

Commit

Permalink
Ensuring that close is called if #initialize fails
Browse files Browse the repository at this point in the history
  • Loading branch information
Tony Novak committed May 12, 2015
1 parent 0e2cb40 commit 7fddb7c
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 1 deletion.
3 changes: 3 additions & 0 deletions lib/roo/base.rb
Expand Up @@ -32,6 +32,9 @@ def initialize(filename, options = {}, _file_warning = :error, _tmpdir = nil)
@last_column = {}

@header_line = 1
rescue => e # clean up any temp files, but only if an error was raised
close
raise e
end

def close
Expand Down
3 changes: 3 additions & 0 deletions lib/roo/excelx.rb
Expand Up @@ -288,6 +288,9 @@ def initialize(filename_or_stream, options = {})
end

super
rescue => e # clean up any temp files, but only if an error was raised
close
raise e
end

def method_missing(method,*args)
Expand Down
3 changes: 3 additions & 0 deletions lib/roo/open_office.rb
Expand Up @@ -38,6 +38,9 @@ def initialize(filename, options={})
@font_style_definitions = Hash.new
@comment = Hash.new
@comments_read = Hash.new
rescue => e # clean up any temp files, but only if an error was raised
close
raise e
end

def method_missing(m,*args)
Expand Down
8 changes: 7 additions & 1 deletion test/test_roo.rb
Expand Up @@ -64,7 +64,7 @@ def with_each_spreadsheet(options)
yield Roo::Spreadsheet.open(File.join(TESTDIR,
fixture_filename(options[:name], format)))
rescue => e
raise e, "#{e.message} for #{format}", e.backtrace
raise e, "#{e.message} for #{format}", e.backtrace unless options[:ignore_errors]
end
end
end
Expand Down Expand Up @@ -2079,4 +2079,10 @@ def test_close
assert !File.exists?(tempdir), "Expected #{tempdir} to be cleaned up, but it still exists"
end
end

def test_cleanup_on_error
old_temp_files = Dir.open(Dir.tmpdir).to_a
with_each_spreadsheet(:name=>'non_existent_file', :ignore_errors=>true) do |oo|; end
assert_equal Dir.open(Dir.tmpdir).to_a, old_temp_files
end
end # class

0 comments on commit 7fddb7c

Please sign in to comment.