Skip to content

Commit

Permalink
Implement Dir.glob base option
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisBr committed Jan 4, 2018
1 parent 425743f commit 4c3a2c0
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
26 changes: 22 additions & 4 deletions core/src/main/java/org/jruby/RubyDir.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
import org.jruby.util.JRubyFile;
import org.jruby.util.ByteList;
import org.jruby.util.StringSupport;
import org.jruby.util.TypeConverter;

/**
* .The Ruby built-in class Dir.
Expand Down Expand Up @@ -206,17 +207,34 @@ private static ByteList globArgumentAsByteList(ThreadContext context, IRubyObjec
* with each filename is passed to the block in turn. In this case, Nil is
* returned.
*/
@JRubyMethod(required = 1, optional = 1, meta = true)
@JRubyMethod(required = 1, optional = 2, meta = true)
public static IRubyObject glob(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
Ruby runtime = context.runtime;
int flags = args.length == 2 ? RubyNumeric.num2int(args[1]) : 0;
int flags = 0;
String dir, base = "";

if(args.length == 3) {
RubyHash hash = (RubyHash) args[2];
base = (String) hash.get(context.runtime.newSymbol("base"));
flags = RubyNumeric.num2int(args[1]);
} else if(args.length == 2) {
IRubyObject tmp = TypeConverter.checkHashType(runtime, args[1]);
if(tmp.isNil()){
flags = RubyNumeric.num2int(args[1]);
} else {
RubyHash hash = (RubyHash) args[1];
base = (String) hash.get(context.runtime.newSymbol("base"));
}
}

List<ByteList> dirs;
IRubyObject tmp = args[0].checkArrayType();
if (tmp.isNil()) {
dirs = Dir.push_glob(runtime, runtime.getCurrentDirectory(), globArgumentAsByteList(context, args[0]), flags);
dir = base.isEmpty() ? runtime.getCurrentDirectory() : base;
dirs = Dir.push_glob(runtime, dir, globArgumentAsByteList(context, args[0]), flags);
} else {
dirs = dirGlobs(context, getCWD(runtime), ((RubyArray) tmp).toJavaArray(), flags);
dir = base.isEmpty() ? getCWD(runtime) : base;
dirs = dirGlobs(context, dir, ((RubyArray) tmp).toJavaArray(), flags);
}

if (block.isGiven()) {
Expand Down
10 changes: 10 additions & 0 deletions spec/ruby/core/dir/glob_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,14 @@
end
end
end

ruby_version_is "2.5" do
it "accepts base: parameter" do
Dir.mkdir 'foo'
dir = File.join(@cwd, foo)
files = %w[a/foo.c c/bar.c].map {|n| File.join(dir, n)}
files.each {|n| File.write(n, "")}
assert_equal(files, Dir.glob("*/*.c", base: dir))
end
end
end

0 comments on commit 4c3a2c0

Please sign in to comment.