From f047918d094bba0379149bb839d274ec243c951c Mon Sep 17 00:00:00 2001 From: akr Date: Fri, 3 Oct 2003 16:36:24 +0000 Subject: [PATCH] * lib/pathname.rb (initialize): duplicate and freeze argument. (to_s): return duplicated string. (children): new method. (each_line): new alias to foreachline. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@4662 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 7 +++++++ lib/pathname.rb | 27 ++++++++++++++++++++++++--- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/ChangeLog b/ChangeLog index cc7aaa3c07..2fe7f4c1f4 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,10 @@ +Sat Oct 4 01:33:46 2003 Tanaka Akira + + * lib/pathname.rb (initialize): duplicate and freeze argument. + (to_s): return duplicated string. + (children): new method. + (each_line): new alias to foreachline. + Fri Oct 3 16:13:19 2003 GOTOU Yuuzou * ext/openssl/ossl_asn1.c: add DER encoder and decoder. diff --git a/lib/pathname.rb b/lib/pathname.rb index d48cef6857..1182a975ed 100644 --- a/lib/pathname.rb +++ b/lib/pathname.rb @@ -2,9 +2,14 @@ # # Author:: Tanaka Akira +# Pathname represents a pathname which locates a file in a filesystem. +# +# Pathname is immutable. It has no method for destructive update. +# class Pathname def initialize(path) - @path = path.to_str + @path = path.to_str.dup + @path.freeze end def ==(other) @@ -24,7 +29,7 @@ class Pathname end def to_s - @path + @path.dup end alias to_str to_s @@ -230,11 +235,22 @@ class Pathname end end + # Pathname#children returns the children of the directory as an array of + # pathnames. I.e. it is similar to Pathname#entries except '.' and '..' + # is not returned. + def children + Dir.entries(@path).map {|f| + f == '.' || f == '..' ? nil : Pathname.new(f) + }.compact + end + end # IO class Pathname def foreachline(*args, &block) IO.foreach(@path, *args, &block) end + alias each_line foreachline + def read(*args) IO.read(@path, *args) end def readlines(*args) IO.readlines(@path, *args) end def sysopen(*args) IO.sysopen(@path, *args) end @@ -481,7 +497,6 @@ if $0 == __FILE__ assert_equal('a/b/../../../../c/../d', Pathname.new('a/b/../../../../c/../d').cleanpath(true).to_s) end - def test_cleanpath_no_symlink assert_equal('/', Pathname.new('/').cleanpath.to_s) assert_equal('/', Pathname.new('//').cleanpath.to_s) @@ -521,5 +536,11 @@ if $0 == __FILE__ assert_equal('../../d', Pathname.new('a/b/../../../../c/../d').cleanpath.to_s) end + def test_destructive_update + path = Pathname.new("a") + path.to_s.replace "b" + assert_equal(Pathname.new("a"), path) + end + end end