Created
May 10, 2009 08:38
-
-
Save knu/109550 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Enumerator | |
class Buffer | |
attr_accessor :status | |
def initialize(yielder, initial_status = nil) | |
@buffer = [] | |
@yielder = yielder | |
@status = initial_status | |
end | |
def push(item) | |
@buffer.push(item) | |
end | |
alias << push | |
def pop | |
@buffer.pop | |
end | |
def clear | |
@buffer.clear | |
self | |
end | |
def empty? | |
@buffer.empty? | |
end | |
def size | |
@buffer.size | |
end | |
def flush | |
return false if @buffer.empty? | |
@yielder.yield(@buffer) | |
@buffer = [] | |
true | |
end | |
end | |
end | |
module Enumerable | |
def buffer(initial_status = nil, &block) | |
Enumerator.new { |yielder| | |
buffer = Enumerator::Buffer.new(yielder, initial_status) | |
each { |*args| | |
case args.size | |
when 0 | |
block.call(buffer) | |
when 1 | |
block.call(args.first, buffer) | |
else | |
block.call(args, buffer) | |
end | |
} | |
buffer.flush | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment