From 08346e7267b4f17ae207d67543d5f78c2541dc86 Mon Sep 17 00:00:00 2001 From: schneems Date: Tue, 27 Oct 2020 13:54:23 -0500 Subject: [PATCH] Introduce Pathname.mktmpdir When I want to create a tmpdir I often want to manipulate it as a pathname. By introducing Pathname.mktmpdir I can get this behavior. Currently I must: ```ruby Dir.mktmpdir do |dir| dir = Pathname(dir) # ... code end ``` I would like to be able to instead: ```ruby Pathname.mktmpdir do |dir| # ... code end ``` --- ext/pathname/lib/pathname.rb | 17 +++++++++++++++++ test/pathname/test_pathname.rb | 8 ++++++++ 2 files changed, 25 insertions(+) diff --git a/ext/pathname/lib/pathname.rb b/ext/pathname/lib/pathname.rb index 338b7a3dc0..52e1d5cfbb 100644 --- a/ext/pathname/lib/pathname.rb +++ b/ext/pathname/lib/pathname.rb @@ -603,3 +603,20 @@ class Pathname # * FileUtils * end end +class Pathname # * tmpdir * + # Creates a tmp directory and wraps the returned path in a Pathname object. + # + # See Dir.mktmpdir + def self.mktmpdir + require 'tmpdir' unless defined?(Dir.mktmpdir) + if block_given? + Dir.mktmpdir do |dir| + dir = self.new(dir) + yield dir + end + else + self.new(Dir.mktmpdir) + end + end +end + diff --git a/test/pathname/test_pathname.rb b/test/pathname/test_pathname.rb index a23dc21ae3..edd96e2724 100644 --- a/test/pathname/test_pathname.rb +++ b/test/pathname/test_pathname.rb @@ -1333,6 +1333,14 @@ class TestPathname < Test::Unit::TestCase } end + def test_mktmpdir + Pathname.mktmpdir do |dir| + assert_equal Pathname(dir), dir + assert dir.directory? + assert dir.exist? + end + end + def test_s_getwd wd = Pathname.getwd assert_kind_of(Pathname, wd)