Created
February 12, 2015 18:26
-
-
Save hawx/8895f7bfa9b38b4ba4e9 to your computer and use it in GitHub Desktop.
simple runner for before/after each/all tasks
This file contains hidden or 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
# Sometimes you want to run a set of blocks before/after | |
# each/all of something. Problem solved. | |
# | |
# @example | |
# | |
# class CountDown < Runner | |
# before :all do |arr| | |
# arr.collect {|i| i + 1 } | |
# end | |
# | |
# before :all do |arr| | |
# arr.reverse | |
# end | |
# | |
# before :each do |n| | |
# print "in " | |
# end | |
# | |
# after :each do |n| | |
# print n.to_s + "!\n" | |
# end | |
# | |
# after :all do | |
# puts "LIFT OFF!" | |
# end | |
# | |
# def self.from(n) | |
# numbers = (0...n).to_a | |
# numbers = run(:before, :all, numbers) | |
# | |
# numbers.collect! do |n| | |
# run :before, :each, n | |
# run :after, :each, n | |
# end | |
# | |
# run :after, :all | |
# end | |
# end | |
# | |
# CountDown.from(5) | |
# #=> in 5! | |
# #=> in 4! | |
# #=> in 3! | |
# #=> in 2! | |
# #=> in 1! | |
# #=> LIFT OFF! | |
# | |
class Runner | |
# In "real life" you probably wouldn't be able to use the | |
# new 1.9 syntax, but it is nicer. | |
@@blocks = { | |
before: { | |
all: [], | |
each: [] | |
}, | |
after: { | |
all: [], | |
each: [] | |
} | |
} | |
# @example | |
# | |
# before :all do |arg| | |
# p arg | |
# end | |
# | |
def self.before(a, &block) | |
@@blocks[:before][a] << block | |
end | |
# @example | |
# | |
# after :each do | |
# p "bye" | |
# end | |
# | |
def self.after(a, &block) | |
@@blocks[:after][a] << block | |
end | |
# Call each block in turn, use with common sense. | |
# Passes +args+ to the first block that is run, in order | |
# that they were defined, then passes result of that to | |
# the next block and so on. | |
# | |
# @example | |
# | |
# def read_all(files) | |
# files = run :before, :all, files | |
# | |
# files.collect! do |file| | |
# file = run :before, :each, file | |
# # do something to +file+ | |
# run :after, :each, file | |
# end | |
# | |
# files = run :after, :all, files | |
# end | |
# | |
# @return | |
# Result of the last executed block. | |
# | |
def self.run(time, a, *args) | |
r = nil | |
@@blocks[time][a].each do |b| | |
if r | |
r = b.call(r) | |
else | |
r = b.call(*args) | |
end | |
end | |
r | |
end | |
# def run(time, a, *args); self.class.run(time, a, *args); end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment