Created
June 14, 2016 17:37
-
-
Save porras/be4aee02b15e16bb61d1c9ec9210426c 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 CachedEnumerable | |
include Enumerable | |
def initialize(wrapped = nil) | |
@enumerator = case wrapped | |
when Enumerator | |
wrapped | |
when Enumerable | |
wrapped.to_enum | |
when NilClass | |
Enumerator.new { |e| yield(e) } | |
else | |
raise ArgumentError, "#{self.class.name} must be initialized with an Enumerator, an Enumerable or a block, not a #{wrapped.class.name}" | |
end | |
@cache = [] | |
end | |
def each(&block) | |
@cache.each(&block) | |
while next_item = @enumerator.next | |
@cache << next_item | |
block.call(next_item) | |
end | |
rescue StopIteration | |
# nothing | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment