Skip to content

Instantly share code, notes, and snippets.

@aviddiviner
Last active August 29, 2015 13:56
Show Gist options
  • Save aviddiviner/9166616 to your computer and use it in GitHub Desktop.
Save aviddiviner/9166616 to your computer and use it in GitHub Desktop.
Enumerable monkey patches
module Enumerable
# Iterate through a list of things, printing out dots every N items.
#
# cards.each_with_progress do |card|
# ...
# end
#
def each_with_progress(dot_interval = 20)
progress = 0
each do |item|
progress += 1
yield item
print '.' if progress % dot_interval == 0
end
end
# Map each item to its responses to the given fields.
# Returns a hash of fields => values per row.
#
# snapshots.map_send(:id, :status, :progress)
# # => [ {:id=>"fe93d6d6", :status=>"complete", :progress=>100},
# {:id=>"499dd861", :status=>"working", :progress=>65}, ... ]
#
def map_send(*fields)
map do |item|
fields.reduce({}){ |m, f| m[f] = item.send(f); m }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment