Skip to content

Commit

Permalink
add Hook object
Browse files Browse the repository at this point in the history
  • Loading branch information
dchelimsky committed Jun 19, 2010
1 parent be8b82d commit 6a7bd48
Showing 1 changed file with 29 additions and 8 deletions.
37 changes: 29 additions & 8 deletions lib/rspec/core/hooks.rb
@@ -1,6 +1,27 @@
module RSpec
module Core
module Hooks
class Hook
attr_reader :options

def initialize(options, block)
@options = options
@block = block
end

def options_apply?(group)
!group || group.all_apply?(options)
end

def call
@block.call
end

def to_proc
@block
end
end

def hooks
@hooks ||= {
:around => { :each => [] },
Expand All @@ -10,18 +31,20 @@ def hooks
end

def before(scope=:each, options={}, &block)
hooks[:before][scope] << [options, block]
hooks[:before][scope] << Hook.new(options, block)
end

def after(scope=:each, options={}, &block)
hooks[:after][scope] << [options, block]
hooks[:after][scope] << Hook.new(options, block)
end

def around(scope=:each, &block)
RSpec::deprecate("around", "before and after")
hooks[:around][scope] << block
end

# Runs the hook in the context of the example. If no
# example is provided, just callse the hook directly
def run_hook(hook, scope, example=nil, options={})
if options[:reverse]
hooks[hook][scope].reverse.each &run_hook_in(example)
Expand All @@ -33,9 +56,9 @@ def run_hook(hook, scope, example=nil, options={})
def run_hook!(hook, scope, example, options={})
until hooks[hook][scope].empty?
if options[:reverse]
example.instance_eval &hooks[hook][scope].shift.last
example.instance_eval &hooks[hook][scope].shift
else
example.instance_eval &hooks[hook][scope].pop.last
example.instance_eval &hooks[hook][scope].pop
end
end
end
Expand All @@ -45,15 +68,13 @@ def run_hook_filtered(hook, scope, group, example)
end

def find_hook(hook, scope, group)
hooks[hook][scope].select do |filters, block|
!group || group.all_apply?(filters)
end
hooks[hook][scope].select {|hook| hook.options_apply?(group)}
end

private

def run_hook_in(example)
lambda {|arr| example ? example.instance_eval(&arr.last) : arr.last.call}
lambda {|hook| example ? example.instance_eval(&hook) : hook.call}
end
end
end
Expand Down

0 comments on commit 6a7bd48

Please sign in to comment.