Skip to content

Instantly share code, notes, and snippets.

@charlietanksley
Created September 26, 2012 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlietanksley/3789095 to your computer and use it in GitHub Desktop.
Save charlietanksley/3789095 to your computer and use it in GitHub Desktop.
methods in blocks
class NginxLog
[snip]
def read
raw = read_source
raw.extend(Seeder::LazyEnumerable)
entries = raw.take_with_block(@count, &:interesting?)
raw.map { |entry| parse_entry(entry) }
end
def interesting?(line)
line !~ /\/status\/heartbeat / && line =~ /GET/
end
end
module Seeder
module LazyEnumerable
# Public: Like Enumerable#take, but only takes the items for which
# the block is true. This can only be mixed in to objects that
# already mixin Enumerable.
#
# count - an Integer; the number of entries you want.
# block - we'll only return objects for which this is true.
#
# Examples:
#
# a = [1, 2, 3, 4, 5, 6]
# a.extend(Seeder::LazyEnumerable)
# a.take_with_block(2) { |x| x.even? }
# #=> [2, 4]
# a.take_with_block(10, :&odd?)
# #=> [1, 3, 5]
#
# Returns an Enumerable (presumably of the kind you passed in.
def take_with_block(count, &block)
array = self.dup
results = []
array.each do |entry|
if yield(entry)
results.push entry if results.count < count
break if results.count >= count
end
end
results
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment