Skip to content

Commit

Permalink
Added Dir#each_child iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija committed Aug 10, 2017
1 parent 95420aa commit 606f283
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
15 changes: 15 additions & 0 deletions spec/std/dir_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,21 @@ describe "Dir" do
filenames << filename
end

filenames.includes?(".").should be_true
filenames.includes?("..").should be_true
filenames.includes?("dir_spec.cr").should be_true
end

it "gets child iterator" do
filenames = [] of String

iter = Dir.new(__DIR__).each_child
iter.each do |filename|
filenames << filename
end

filenames.includes?(".").should be_false
filenames.includes?("..").should be_false
filenames.includes?("dir_spec.cr").should be_true
end

Expand Down
25 changes: 25 additions & 0 deletions src/dir.cr
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,10 @@ class Dir
end
end

def each_child
ChildIterator.new(self)
end

# Returns an array containing all of the filenames except for `.` and `..`
# in the given directory.
def children : Array(String)
Expand Down Expand Up @@ -305,6 +309,27 @@ class Dir
self
end
end

private struct ChildIterator
include Iterator(String)

def initialize(@dir : Dir)
end

def next
excluded = {".", ".."}
loop do
break unless entry = @dir.read

This comment has been minimized.

Copy link
@RX14

RX14 Aug 10, 2017

Member

Ok so this should use while entry = @dir.read

return entry unless excluded.includes?(entry)
end
stop
end

def rewind
@dir.rewind
self
end
end
end

require "./dir/*"

0 comments on commit 606f283

Please sign in to comment.