From ffc6edcd682d62d3510a4a490a9c0fca5a27e3f6 Mon Sep 17 00:00:00 2001 From: PikachuEXE Date: Fri, 10 Mar 2017 17:32:30 +0800 Subject: [PATCH] * Result block value for SevenZipReader.open & .open_file They were always returning `nil` (from SevenZipReader#close_file) Also changed &block + block.call to block_given? + yield --- lib/seven_zip_ruby/seven_zip_reader.rb | 24 ++++++++++++------ spec/seven_zip_ruby_spec.rb | 34 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/lib/seven_zip_ruby/seven_zip_reader.rb b/lib/seven_zip_ruby/seven_zip_reader.rb index 378ad4f..90b92fa 100644 --- a/lib/seven_zip_ruby/seven_zip_reader.rb +++ b/lib/seven_zip_ruby/seven_zip_reader.rb @@ -98,13 +98,17 @@ class << self # SevenZipRuby::Reader.open(stream) do |szr| # szr.extract(:all, "path_to_dir") # end - def open(stream, param = {}, &block) # :yield: szr + def open(stream, param = {}) # :yield: szr szr = self.new szr.open(stream, param) - if (block) + # Using `block_given?`, `yield` & omitting `&block` + # is faster + # Ref: https://github.com/JuanitoFatas/fast-ruby#proccall-and-block-arguments-vs-yieldcode + if block_given? begin - block.call(szr) - szr.close + yield(szr).tap do + szr.close + end ensure szr.close_file end @@ -135,13 +139,17 @@ def open(stream, param = {}, &block) # :yield: szr # szr = SevenZipRuby::SevenZipReader.open_file("filename.7z") # # Read and extract archive. # szr.close - def open_file(filename, param = {}, &block) # :yield: szr + def open_file(filename, param = {}) # :yield: szr szr = self.new szr.open_file(filename, param) - if (block) + # Using `block_given?`, `yield` & omitting `&block` + # is faster + # Ref: https://github.com/JuanitoFatas/fast-ruby#proccall-and-block-arguments-vs-yieldcode + if block_given? begin - block.call(szr) - szr.close + yield(szr).tap do + szr.close + end ensure szr.close_file end diff --git a/spec/seven_zip_ruby_spec.rb b/spec/seven_zip_ruby_spec.rb index 698405a..7a41a43 100644 --- a/spec/seven_zip_ruby_spec.rb +++ b/spec/seven_zip_ruby_spec.rb @@ -97,6 +97,40 @@ end end + describe "singleton method: open" do + context "called with block" do + let(:block_value) { "Block value" } + + subject(:returned_result) do + File.open(SevenZipRubySpecHelper::SEVEN_ZIP_FILE, "rb") do |file| + SevenZipRuby::SevenZipReader.open(file) do |_szr| + block_value + end + end + end + + it "returns block value" do + should eq(block_value) + end + end + end + + describe "singleton method: open_file" do + context "called with block" do + let(:block_value) { "Block value" } + + subject(:returned_result) do + SevenZipRuby::SevenZipReader.open_file(SevenZipRubySpecHelper::SEVEN_ZIP_FILE) do |_szr| + block_value + end + end + + it "returns block value" do + should eq(block_value) + end + end + end + example "extract archive" do File.open(SevenZipRubySpecHelper::SEVEN_ZIP_FILE, "rb") do |file| SevenZipRuby::SevenZipReader.open(file) do |szr|