Skip to content

Commit 01fc436

Browse files
committed
Implement Pathname#chdir
1 parent f3d2367 commit 01fc436

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

ext/pathname/pathname.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ static ID id_binwrite;
1212
static ID id_birthtime;
1313
static ID id_blockdev_p;
1414
static ID id_chardev_p;
15+
static ID id_chdir;
1516
static ID id_chmod;
1617
static ID id_chown;
1718
static ID id_ctime;
@@ -1248,6 +1249,24 @@ path_opendir(VALUE self)
12481249
return rb_block_call(rb_cDir, id_open, 1, args, 0, 0);
12491250
}
12501251

1252+
/*
1253+
* Changes the current path to the referenced directory.
1254+
*
1255+
* See Dir.chdir.
1256+
*/
1257+
static VALUE
1258+
path_chdir(VALUE self)
1259+
{
1260+
VALUE args[1];
1261+
1262+
if(rb_block_given_p()) {
1263+
args[0] = get_strpath(self);
1264+
return rb_block_call(rb_cDir, id_chdir, 1, args, 0, 0);
1265+
} else {
1266+
return rb_funcall(rb_cDir, id_chdir, 1, get_strpath(self));
1267+
}
1268+
}
1269+
12511270
static VALUE
12521271
each_entry_i(RB_BLOCK_CALL_FUNC_ARGLIST(elt, klass))
12531272
{
@@ -1470,6 +1489,7 @@ path_f_pathname(VALUE self, VALUE str)
14701489
* - #each_entry(&block)
14711490
* - #mkdir(*args)
14721491
* - #opendir(*args)
1492+
* - #chdir(*args)
14731493
*
14741494
* === IO
14751495
*
@@ -1589,6 +1609,7 @@ Init_pathname(void)
15891609
rb_define_method(rb_cPathname, "mkdir", path_mkdir, -1);
15901610
rb_define_method(rb_cPathname, "rmdir", path_rmdir, 0);
15911611
rb_define_method(rb_cPathname, "opendir", path_opendir, 0);
1612+
rb_define_method(rb_cPathname, "chdir", path_chdir, 0);
15921613
rb_define_method(rb_cPathname, "each_entry", path_each_entry, 0);
15931614
rb_define_method(rb_cPathname, "unlink", path_unlink, 0);
15941615
rb_define_method(rb_cPathname, "delete", path_unlink, 0);
@@ -1611,6 +1632,7 @@ InitVM_pathname(void)
16111632
id_birthtime = rb_intern("birthtime");
16121633
id_blockdev_p = rb_intern("blockdev?");
16131634
id_chardev_p = rb_intern("chardev?");
1635+
id_chdir = rb_intern("chdir");
16141636
id_chmod = rb_intern("chmod");
16151637
id_chown = rb_intern("chown");
16161638
id_ctime = rb_intern("ctime");

test/pathname/test_pathname.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1416,6 +1416,19 @@ def test_opendir
14161416
}
14171417
end
14181418

1419+
def test_chdir
1420+
with_tmpchdir('rubytest-pathname') {|dir|
1421+
prev = Dir.pwd
1422+
Pathname("foo").mkdir
1423+
Pathname("foo").chdir
1424+
assert_equal("#{prev}/foo", Dir.pwd)
1425+
Pathname("..").chdir do
1426+
assert_equal(prev, Dir.pwd)
1427+
end
1428+
assert_equal("#{prev}/foo", Dir.pwd)
1429+
}
1430+
end
1431+
14191432
def test_find
14201433
with_tmpchdir('rubytest-pathname') {|dir|
14211434
open("a", "w") {}

0 commit comments

Comments
 (0)